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
1 Like

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
}
2 Likes

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.

4 Likes

@OptimisticPeach , @quadrupleslap :

Thanks! The question I asked was not exactly the question I intended to ask. The answer however (found in Destructuring and Pattern Matching ) is:

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.