Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does pattern matching on &Option<T> yield something of type Some(&T)?

I have a tiny playground example here

fn main() {
    let l = Some(3);
    match &l {
        None => {}
        Some(_x) => {} // x is of type &i32
    }
}

I'm pattern matching on &Option and if I use Some(x) as a branch, why is x of type &i32?

like image 246
nz_21 Avatar asked Apr 11 '19 04:04

nz_21


1 Answers

The type of the expression &l you match against is &Option<i32>, so if we are strict the patterns should be &None and &Some(x), and if we use these patterns, the type of x indeed is i32. If we omit the ampersand in the patterns, as you did in your code, it first looks like the patterns should not be able to match at all, and the compiler should throw an error similar to "expected Option, found reference", and indeed this is what the compiler did before Rust version 1.26.

Current versions of Rust support "match ergonomics" introduced by RFC 2005, and matching a reference to an enum against a pattern without the ampersand is now allowed. In general, if your match expression is only a reference, you can't move any members out of the enum, so matching a reference against Some(x) is equivalent to matching against the pattern &Some(ref x), i.e. x becomes a reference to the inner value of the Option. In your particular case, the inner value is an i32, which is Copy, so you would be allowed to match against &Some(x) and get an i32, but this is not possible for general types.

The idea of the RFC is to make it easier to get the ampersands and refs in patterns right, but I'm not completely convinced whether the new rules actually simplified things, or whether they added to the confusion by making things magically work in some cases, thereby making it more difficult for people to get a true understanding of the underlying logic. (This opinion is controversial – see the comments.)

like image 173
Sven Marnach Avatar answered Nov 15 '22 11:11

Sven Marnach