Isaac Ferreira
Isaac Ferreira

Reputation: 436

Why sometimes a variable is dereferenced in match?

It's very common to see a variable being dereferenced inside match expression. Rust's libcore uses this in some functions:

impl<T> Option<T> {
    pub fn is_some(&self) -> bool {
        match *self {
                Some(_) => true,
                None => false,
            }
        }
    }
}

When should we use it and when we shouldn't? Does this have memory or performance penality?

Upvotes: 2

Views: 306

Answers (1)

Peter Hall
Peter Hall

Reputation: 58875

Match patterns must be the same type as the expression. If the expression is a reference then the patterns must also match against references.

In a method that takes &self (a reference), this:

match self {
    &Some(_) => true,
    &None => false,
}

is equivalent to:

match *self {
    Some(_) => true,
    None => false,
}

There is no performance difference; they should end up compiling to the same thing (proof).

The second one is considered better style because it uses fewer characters, and makes the patterns less noisy and repetitive. With default settings, Clippy will warn you if you do the first one.

In a lot of cases, including this one, you can omit the references in the patterns altogether:

match self {
    Some(_) => true,
    None => false,
}

This is a kind of syntactic sugar, where the &s are automatically added in unambiguous cases. I can't tell you exactly when this is allowed, but the compiler certainly will tell you when it's not! ;) In practice, I tend to write match statements like this, without explicit references, and then fix it up if the compiler complains.

Upvotes: 3

Related Questions