rust - 在不修改 args 的情况下采用第一个参数的干净方式

该程序应采用如下参数:<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);
    });

相似文章

linux - 使用 fork 使 process 在后台运行

我正在尝试制作一个简单的外壳。当我在孩子中执行命令并等待它时,代码工作正常。但是,当我想在后台执行它时,程序只是挂在那里,提示符号没有出现。我还应该添加什么代码来让我的孩子process完成它的工作,...

随机推荐

最新文章