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

标签 rust structopt

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

  • --version(将打印出版本号并退出)
  • --out(这是一些输出文件的路径,魔法将被注入(inject)其中)。

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

这就是我所拥有的,但我想知道是否有任何方法可以只使用 structopt 来做到这一点?

看来我最终可能需要将所有参数设为可选并自己进行所有验证...

#![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());
}

最佳答案

使用required_unless:

#[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>,
}
$ ./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_if
  • requires_ifs
  • required_if
  • required_ifs
  • requires_all

旁注:您根本不需要在此代码中使用 #![feature(custom_attribute)]

关于rust - 如何根据 structopt 中另一个参数的存在使参数可选?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49877823/

相关文章:

loops - 具有生命周期界限的递归函数内循环中的借用检查器错误

json - 如何将 Serde 与包含不同对象的 JSON 数组一起使用以获取成功和错误?

rust - 如何在所有子命令都为可选的情况下创建StructOpt命令

rust - 如何根据泛型类型参数赋予不同的值?

loops - 为什么我不能在两个不同的映射函数中可变地借用变量?

rust - 是否有更清晰的方式来表示取消引用原始指针并在 Rust 中应用它们的功能?

rust - 如何在带有 structopt crate 的子命令后使用 CLI 参数?

rust - StructOpt - 如何为 Vec 提供默认值?

rust - 如何使用structopt将不可能的值附加到结构上?