首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据另一个参数在structopt中的存在而使参数可选?

如何根据另一个参数在structopt中的存在而使参数可选?
EN

Stack Overflow用户
提问于 2018-04-17 12:12:38
回答 2查看 4.3K关注 0票数 11

我有一个命令行工具,它有两个可能的参数:

  • --version (它将打印版本号并退出)
  • --out (这是通向某个输出文件的路径,其中将注入魔法)。

如果用户通过了--version,我不关心--out,因为我打印了版本,完成了,但是,如果他们没有通过--version,我希望--out是必需的。

这就是我所拥有的,但是我想知道是否有任何方法可以只用structopt来完成这个任务呢?

看来我最终可能需要让我的所有论点都是可选的,并且自己做所有的验证.

代码语言:javascript
复制
#![feature(custom_attribute)]
#[macro_use]
extern crate structopt;

use structopt::StructOpt;
use std::path::PathBuf;

#[derive(Debug, StructOpt)]
#[structopt(name = "structopt_playing", about = "Just playing")]
struct Opt {
    #[structopt(short = "v", long = "version")]
    version: bool,

    #[structopt(short = "o", long = "out", parse(from_os_str))]
    output_file: Option<PathBuf>,
}

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

fn main() {

    let opt = Opt::from_args();
    if opt.version {
        println!("Version: {}", VERSION);
        return;
    }

    if !opt.output_file.is_some() {
        println!("Oh, now I feel like I'm alone...you need to pass --out");
        return;
    }

    println!("Now I'm going to need to do something with {:?}", 
        opt.output_file.unwrap());
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-17 14:38:55

使用required_unless

代码语言:javascript
复制
#[derive(Debug, StructOpt)]
#[structopt(name = "structopt_playing", about = "Just playing")]
struct Opt {
    #[structopt(short = "v", long = "version")]
    version: bool,

    #[structopt(short = "o", long = "out", parse(from_os_str), required_unless = "version")]
    //                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    output_file: Option<PathBuf>,
}
代码语言:javascript
复制
$ ./target/debug/stropt
error: The following required arguments were not provided:
    --out <output_file>

USAGE:
    stropt --out <output_file>

For more information try --help

$ ./target/debug/stropt --out hello
Now I'm going to need to do something with "hello"

$ ./target/debug/stropt --version
Version: 0.1.0

Clap提供了大量相关的配置选项:

  • required_unless
  • required_unless_all
  • required_unless_one
  • conflicts_with
  • conflicts_with_all
  • requires
  • requires_if
  • requires_ifs
  • required_if
  • required_ifs
  • requires_all

附带注意:您根本不需要在这段代码中使用#![feature(custom_attribute)]

票数 19
EN

Stack Overflow用户

发布于 2018-04-17 12:37:50

我将使用以下子命令:

代码语言:javascript
复制
#![feature(custom_attribute)]
#[macro_use] extern crate structopt;

use structopt::StructOpt;
use std::path::PathBuf;

#[derive(StructOpt)]
#[structopt(name = "test")]
enum Git {
    #[structopt(name = "--version")]
    Version,
    #[structopt(name = "--out")]
    Fetch(PathBuf),
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49877823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档