I have an enum:
#[derive(PartialEq, Eq)]
enum Foo {
A,
B(usize),
}
I can use it in if
statements involving other logic like baz
:
fn bar(foo: &Foo, baz: bool) {
if foo == &Foo::B(3) || baz {
println!("Do stuff")
}
}
However, this won't compile:
fn bar(foo: &Foo, baz: bool) {
if foo == &Foo::B(_) || baz {
println!("Do stuff")
}
}
How do I use it in an if
statement when I don't care what value B
contains?
You can use
std::mem::discriminant
:If you have to test this a lot, I advice you to implement a method for it:
It's probably easier to use a
match
in this case:Alternatively with an
if let
:I'm not sure you can pull it all into a single condition easily, which makes you repeat
do_stuff
unfortunately.