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

时光总嘲笑我的痴心妄想 提交于 2020-01-16 05:25:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/55625001/why-does-pattern-matching-on-optiont-yield-something-of-type-somet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!