Match vectors by content

Hi all,
I have a finite set of vectors of specific length and I would like to use them in a match expression (or something similar). However a match on a vector does not match the content.
Here is a small testcode:

fn main() {
    let a = vec![2,3,4];
    let ref1 = vec![1,2,3];
    let ref2 = vec![2,3,4];
    match a {
        ref1 => println!("1,2,3"),
        ref2 => println!("2,3,4"),
        _ => println!("neither")
    }
}

This will always print "1,2,3" and the rest is marked as unreachable pattern.
Is there a standard way to match vectors or should I utilize a big if-then-else and check the vector against all reference-vectors?
Thanks

match arms must have patterns with compile time known constants. a vector is not. your code doesn't match against the values of the variables ref1 or ref2, but matches anything and bind a new variable ref1 to the value, so the first match arm always wins, and the rest are dead code.

1 Like

Yes I figured that out. Is there something more idiomatic I can use than

if a == ref1 {
   ...
} else if a == ref2 {
   ...
} else {
   ...
}  

or is this the way to go?

if the values of ref1 and ref2 etc are only known at runtime, then a chain of if else is the simple way to go (you have alternatives like using a hash map to store the continuation, but that's not something I would normally use)

if those patterns only contains compile time literal values, you can use the slice pattern, something like this:

fn main() {
    let a = vec![2,3,4];
    match a[..] {
        [1,2,3] => println!("1,2,3"),
        [2,3,4] => println!("2,3,4"),
        _ => println!("neither")
    }
}
1 Like

Thank you.
There are only compile time literals in those vectors. Thus your solution works.