![](/img/trans.png)
[英]How to make an argument optional based on the presence of another one in structopt?
[英]How can I distinguish a multi-occurence option from a subsequent optional argument with structopt?
我正在使用structopt定义可以使用的参数
mfe -s opt1 -s opt2 -s opt2 this_is_an_argument
要么
mfe -s opt1 opt2 opt3 this_is_an_argument
问题在于this_is_an_argument
参数被解析为选项。 我知道我可以在争论之前使用--
但是有更好的解决方案吗?
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
struct CLIArgs {
#[structopt(short = "s", long = "str")]
strings: Vec<String>,
#[structopt(name = "PATH", parse(from_os_str))]
path: Option<PathBuf>,
}
fn main() {
let args = CLIArgs::from_args();
println!("{:?}", args);
}
$ mfe -s foo bar baz /this/is/a/path
CLIArgs { strings: ["foo", "bar", "baz", "/this/is/a/path"], path: None }
我希望将/this/is/a/path
解析为path
,而不必强制使用--
。 也许按照参数的顺序执行某些操作?
所以我找到了以下解决方案:
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
struct CLIArgs {
#[structopt(short = "s", long = "str", raw(number_of_values = "1"))]
strings: Vec<String>,
#[structopt(name = "PATH", parse(from_os_str))]
path: Option<PathBuf>,
}
fn main() {
let args = CLIArgs::from_args();
println!("{:?}", args);
}
请注意,它强制用户以这种方式使用程序:
$ mfe -s foo -s bar -s baz /this/is/a/path
根据您的使用情况,这不方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.