Pattern match on a Vec?

I know that we can do pattern matching on a tuple. Is there a similar way to pattern match on a Vec? I want to be express something like:

this clause matches iff

  • the vec has 3 elems
  • first elem is SOME_CONSTANT
  • capture 2nd elem as x
  • third elem is SOME_OTHER_CONSTANT

Does the following work? On mobile so I can’t try it:

let v = vec![...];
if let &[1, 2, 3] = &v[..3] { 
    // Do something
}
if let &[SOME_CONSTANT, x, SOME_OTHER_CONSTANT] = &v[..3] {
    // Do something with x
}
1 Like

That doesn’t coerce the Vec into a slice. I think you need something like

fn main() {
    let xs = vec![1, 2, 3];
    
    const SOME_CONSTANT: usize = 1;
    const SOME_OTHER_CONSTANT: usize = 3;
    
    if let &[SOME_CONSTANT, x, SOME_OTHER_CONSTANT] = &*xs {
        println!("{}", x);
    } else {
        println!("Match refuted.");
    }
}

Playground Link

Edit: Off-topic, but if you use the feature slice_patterns, you can use up to one .. anywhere in the pattern, which is pretty neat.

3 Likes

@OptimisticPeach , @quadrupleslap :

Thanks! The question I asked was not exactly the question I intended to ask. The answer however (found in https://pzol.github.io/getting_rusty/posts/20140417_destructuring_in_rust/ ) is:

match v.as_slice() {
  [...] => {} ; // slice patterns, as both of you have demonstrated above
}
1 Like