【问题标题】:Can a slice pattern be used to parse command line arguments without cloning?可以使用切片模式在不克隆的情况下解析命令行参数吗?
【发布时间】:2018-09-27 22:42:17
【问题描述】:

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>"),
}

【问题讨论】:

  • 我认为Vec::get 会做你想做的事。
  • 请定义在这种情况下高效对您意味着什么。问“我想探索吗”几乎是基于意见的问题。基于意见的问题与 Stack Overflow 无关。
  • @Shepmaster 我正在学习这门语言,并想避免在某些情况下我已经习惯的.clone()。你说得对,“我想要……”听起来像是一种观点,但它是对原始问题的修改。

标签: rust


【解决方案1】:

从 1.40 开始,“其余”没有稳定的语法。然而 nightly 中有这样的语法:

#![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)

语法identifier @ .. 表示“其余部分”is not finalized yet, and might changed in the future

【讨论】:

猜你喜欢
  • 2020-03-13
  • 2013-06-07
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多