用clap迭代位置参数

时间:2017-05-21 07:26:34

标签: rust clap

说我有以下命令行:

./app foo bar baz

我想从中获取此数组:

["foo", "bar", "baz"]

有没有办法在clap中执行此操作,因为位置参数可以是任意计数?

1 个答案:

答案 0 :(得分:2)

您正在寻找的功能是values_of,您可以像这样使用它:

let matches = App::new("My Super Program")
        .arg(Arg::with_name("something")
            .multiple(true))
        .get_matches();

let iterator = matches.values_of("something");
for el in iterator.unwrap() {
    println!("{:?}", el);
};

如果您不关心保留无效的UTF-8,则更容易的选择是使用values_of_lossy返回实际的Vector(Option<Vec<String>>)而不是迭代器。

let arguments = matches.values_of_lossy("something").unwrap();      
println!("{:?}", arguments);

请记住,您实际上不应该打开实际程序中的值,因为如果没有提供参数,它将在运行时崩溃。唯一的例外是required(true)被设置的参数。调用get_matches时,它们的缺失会导致运行时错误(包含有用的错误消息)。