Should a reference to an enum be dereferenced before it is matched?

Viewed 1273

As a newcomer to Rust, I've stumbled upon two apparently valid ways of running a match on a reference type.

I've defined an enum:

enum Color {
    Red,
    Yellow,
    Green,
    Teal,
    Blue,
    Purple,
}

I want to implement a function that works on a &self reference of an instance of this enum.

I can see two ways to write such a function:

impl Color {
    // Approach #1: Match the reference, using references in each pattern
    fn contains_red(&self) -> bool {
        match self {
            &Color::Red => true,
            &Color::Yellow => true,
            &Color::Purple => true,
            _ => false,
        }
    }

    // Approach #2: Dereference &self and match the patterns directly
    fn contains_blue(&self) -> bool {
        match *self {
            Color::Blue => true,
            Color::Teal => true,
            Color::Purple => true,
            _ => false,
        }
    }
}

I expected that dereferencing &self would be counted as a move, and would cause errors if I called color.contains_blue() on the same instance twice in a row, but this doesn't seem to be the case.

Are these approaches functionally identical? Would one of them break down if I were matching more complex objects?

3 Answers

As of Rust 1.26, the idiomatic solution is neither; you don't have to dereference the value or add & to the patterns:

fn contains_blue(&self) -> bool {
    match self {
        Color::Blue => true,
        Color::Teal => true,
        Color::Purple => true,
        _ => false,
    }
}

This is thanks to improved match ergonomics.

You can also use pattern alternation in this case:

match self {
    Color::Blue | Color::Teal | Color::Purple => true,
    _ => false,
}
Related