为什么 &Option<T> 上的模式匹配产生 Some(&T) 类型的东西? [英] Why does pattern matching on &Option<T> yield something of type Some(&T)?

查看:16
本文介绍了为什么 &Option<T> 上的模式匹配产生 Some(&T) 类型的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很小的 ​​playground 示例这里

I have a tiny playground example here

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,所以如果我们严格,模式应该是 &None&Some(x),如果我们使用这些模式,x 的类型code> 确实是 i32.如果我们像您在代码中所做的那样省略模式中的&符号,首先看起来模式根本不应该匹配,并且编译器应该抛出类似于预期选项,找到引用"的错误,并且确实这是编译器在 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,现在允许将枚举的引用与没有&符号的模式进行匹配.通常,如果您的匹配表达式只是一个引用,则不能将任何成员移出枚举,因此将引用与 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 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.

这篇关于为什么 &amp;Option&lt;T&gt; 上的模式匹配产生 Some(&amp;T) 类型的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆