切片模式可以用于分析命令行参数而不进行克隆吗?

时间:2018-09-27 22:42:18

标签: rust

可以使用slice pattern in Rust来解析命令行参数吗?

我将参数捕获为:let args: Vec<String> = std::env::args().skip(1).collect();

我在想这样的东西,它不能编译:

// example usage: progname run bash ls -la
match args {
    ["run", rest_of_commands[..]] => println!("{:?}", rest_of_commands),
    _ => println!("usage: run <your-command>"),
}

1 个答案:

答案 0 :(得分:2)

从1.29版本开始,“其余”没有稳定的语法。 但是,每晚都有这样的语法:

#![feature(slice_patterns)]

fn main() {
    let args = ["foo", "bar"];
    match args {
        ["run", rest_of_commands..] => println!("{:?}", rest_of_commands),
        _ => println!("usage: run <your-command>"),
    }
}

Permalink to the playground

..表示“其余” is not decided yet, and might changed in the future的语法。