1

Can the slice pattern in Rust be used to parse command line arguments?

I capture the arguments as: let args: Vec<String> = std::env::args().skip(1).collect();

I'm thinking something like this, which doesn't compile:

// example usage: progname run bash ls -la
match args {
    ["run", rest_of_commands[..]] => println!("{:?}", rest_of_commands),
    _ => println!("usage: run <your-command>"),
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sysarcher
  • 75
  • 2
  • 10
  • I think [`Vec::get`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.get) will do what you want. – squiguy Sep 27 '18 at 22:53
  • Please define what **efficiently** means to you in this case. Asking "do I want to explore" is about as opinion-based as a question could be. Opinion-based questions are off-topic for Stack Overflow. – Shepmaster Sep 27 '18 at 23:41
  • @Shepmaster I'm learning the language and wanted to avoid `.clone()` that I've gotten used to in some of these cases. You're right 'Do I want...' sound like an opinion but it was an edit to the original question. – sysarcher Sep 28 '18 at 08:00

1 Answers1

3

As of 1.40, there is no stable syntax for "the rest". There is such a syntax in nightly however:

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

The syntax identifier @ .. to mean "the rest" is not finalized yet, and might changed in the future.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mcarton
  • 27,633
  • 5
  • 85
  • 95
  • thanks for the answer! However, do you have a way to do the conversion from `Vec` returned by `std::env::args().collect()` to an array of `&str` (as in your, and my examples)? – sysarcher Sep 27 '18 at 23:15
  • 1
    @sysarcher [How to match a String against string literals in Rust?](https://stackoverflow.com/q/25383488/155423); [How do I get a slice of a Vec in Rust?](https://stackoverflow.com/q/39785597/155423); [Convert Vec to Vec<&str>](https://stackoverflow.com/q/33216514/155423). – Shepmaster Sep 27 '18 at 23:43