[英]Iterate through positional arguments with clap
假設我有以下命令行:
./app foo bar baz
我想從中得到這個數組:
["foo", "bar", "baz"]
有沒有辦法在clap中執行此操作,因為位置參數可以是任意計數?
您正在尋找的函數是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
時,它們的缺失會導致運行時錯誤(帶有有用的錯誤消息)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.