Slice Pattern Workaround

Currently as of Rust 1.7 the slice pattern syntax is experimental (see issue #23121).

Now here is my problem:

I get passed some commands and these each have a number of subcommands, all separated by whitespace so I took this straight forward approach (which also taught me that this was not yet implemented):

match s.split_whitespace().collect::<Vec<&str>>()
{
    ["command","subcommand",e@_] => TODO /* use e to parse to an enum */,
    _ => Err(ParseRequestError),
}

Is there anything I can do that seems rustic enough to be used instead of slice patterns?

Maybe like this:

let mut args = s.split_whitespace();
match (args.next(), args.next()) {
    (Some("command"), Some("subcommand")) => // process args or args.collect() further
    (Some(_), Some(_)) => // error "unknown command or subcommand"
    (Some(_), None) => // error "no subcommand given"
    (None, None) => // error "no command given"
    _ => unreachable!()  // the (None, Some) case should be impossible
}
1 Like

That's great, thank you!

Edit: I hope it will work that way.…

It will work, but the unreachable! case was too broad. Fixed now. (Of course you can also use the _ pattern for any error case if you don't need to differentiate.)

You should also make your args mutable.

Seems to work out pretty well for me. Thank you once again.