该程序应采用如下参数:<command> n1 n2 n3...
例如mode 1 2 3 3 4
。我想 store <command>
参数字符串并将其余参数传递给构造函数进行解析。
fn main() {
let args = args();
let command = args.skip(1).next().unwrap_or_else(|| {
eprintln!("Command not found; expected one of \"mode\", \"mean\", \"median\" \"range\"");
process::exit(1);
});
let set = DataSet::from_args(args).unwrap_or_else(|err| {
eprintln!("error parsing values: {}", err);
process::exit(1);
});
match command.to_lowercase().trim() {
"mode" => println!("{:?}", set.mode()),
_ => eprintln!("Command not recognised: \"{}\"", command),
}
}
这段代码不起作用,因为args.skip(1).next()...
通过将args
改编成Skip
来消耗args
,所以当我尝试调用DataSet::from_args(args)
时它是无效的,因为它被移到了skip
中。
实现这一目标的最佳方法是什么?我听说 itertools 库可以为 Args
提供一个 nth
方法,但我宁愿不这样做。
回答1
首先,https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.nth:您可以使用 nth(1)
代替 skip(1).next()
。
其次,https://doc.rust-lang.org/1.60.0/src/core/iter/traits/iterator.rs.html#3676-3691实现的。所以你可以在 &mut args
上调用 skip()
。甚至还有一种方法:https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.by_ref:
let command = args.by_ref().skip(1).next().unwrap_or_else(|| {
eprintln!("Command not found; expected one of \"mode\", \"mean\", \"median\" \"range\"");
process::exit(1);
});