If enum = Member, vs if let Member = enum?

I'm curious whether one is better than the other of these:

enum Foo {
    A,
    B,
}
if let Foo::A = foo {
}

versus:

if foo == Foo::A {
}

The first will always work, but the second requires a #[derive(Eq,PartialEq)] annotation on the enum (or a manual implementation).

4 Likes

That's true, but personally I prefer the second if possible, for readability (it feels more "natural" and more common).

They are likely to produce the very same machine code. So better is probably just a matter of options at hand at the time and preference.

2 Likes

You can have the best of both worlds with

if matches!(foo, Foo::A) {}

I like to use pattern matching when I can because it's restricted to "structural" inspection of the scrutinee (I think that's the fancy term for foo in this situation), whereas == can in principle hide any kind of Rust code imaginable, even if in practice you just derive it.

4 Likes