问题描述
我有一个很小的游乐场示例在这里
fn main() {
let l = Some(3);
match &l {
None => {}
Some(_x) => {} // x is of type &i32
}
}
我正在&Option
上进行模式匹配,并且如果我将Some(x)
用作分支,为什么x
类型为&i32
?
I'm pattern matching on &Option
and if I use Some(x)
as a branch, why is x
of type &i32
?
推荐答案
与之匹配的表达式&l
的类型为&Option<i32>
,因此如果我们严格要求模式应为&None
和&Some(x)
,如果我们使用这些模式,则x
的类型确实是i32
.如果我们像您在代码中那样在模式中省略了&"号,则首先看起来这些模式根本无法匹配,并且编译器应引发类似于"expected Option,found reference"的错误,实际上这就是Rust版本1.26之前编译器所做的.
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.
Rust当前版本支持 RFC 2005 ,现在允许将对枚举的引用与不带&符的模式进行匹配.通常,如果您的match表达式仅是引用,则不能将任何成员移出枚举,因此将引用与Some(x)
进行匹配等同于与模式&Some(ref x)
进行匹配,即x
成为引用到Option
的内部值.在您的特殊情况下,内部值是i32
,即Copy
,因此您可以与&Some(x)
匹配并获得i32
,但这对于常规类型是不可能的.
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.
RFC的思想是使正确的模式中的&符号和ref
变得更容易,但是我不完全相信新规则是否实际上简化了事情,或者它们是否通过使规则变得更加混乱在某些情况下,事情会神奇地起作用,从而使人们更难以真正理解底层的逻辑.
The idea of the RFC is to make it easier to get the ampersands and ref
s 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.
这篇关于为什么对& Option< T>进行模式匹配?产生一些Some(& T)类型的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!