简体   繁体   中英

Is it possible to write a generic rust function telling you if a given enum variant is in a container?

In other words, if you have:

enum Foo {
   Bar(String),
   Buzz(i32)
}

Can you write a generic function that checks if a vector contains a particular variant (where the desired variant is the generic argument)?:

fn f<T>(x: Vec<Foo>) -> bool {
    for i in &x {
        if let T(...) = i {
            return true;
        }
    }
    return false;
}

Then call with something like:

assert!(f::<Foo::Buzz>(x));

I think this might be equivalent to asking if matches! could be a generic function instead of a macro.

No, you can't use enum variant as a generic argument because it is not a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM