How can I pattern-match a Vec<T> inside an enum field without nesting matches?

坚强是说给别人听的谎言 提交于 2019-12-10 17:17:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!