问题
Pattern-matching a Vec<T> can be done by using either &v[..] or v.as_slice().
let x = vec![1, 2, 3];
match &x[..] {
[] => println!("empty"),
[_] => println!("one"),
[..] => println!("many"),
}
If I have an enum with a field that contains the Vec I want to match on, I need to create a nested match inside the outer match arm:
enum Test {
Many(Vec<u8>),
Text(String),
}
fn main() {
let x = Test::Many(vec![1, 2, 3]);
match x {
Test::Text(s) => println!("{}", s),
Test::Many(v) => match &v[..] {
[] => println!("empty"),
[_] => println!("one"),
[..] => println!("many"),
}
}
}
What I would like to be able to do, is to match directly on the Vec as in the following example:
match x {
Test::Text(s) => println!("{}", s),
Test::Many([]) => println!("empty"),
Test::Many([_]) => println!("one"),
Test::Many([..]) => println!("many"),
}
I am guessing it was possible before unique vectors got removed? Or am I missing some magic using ref that can solve this?
回答1:
It's not possible to do this directly, unfortunately. However, there is desire to possibly add "Deref patterns", which would allow pattern matching through any types which implement Deref or DerefMut, e.g. one could match on the T inside a Box<T>, or on the [T] "inside" a Vec<T>.
来源:https://stackoverflow.com/questions/28851989/how-can-i-pattern-match-a-vect-inside-an-enum-field-without-nesting-matches