在 Rust 中,将非引用与引用进行模式匹配有何作用?

What does pattern-matching a non-reference against a reference do in Rust?

当使用不包含引用的模式对引用进行模式匹配时会发生什么?

这是一个使用结构模式的例子:

fn main() {
    struct S(u32);
    let S(x) = &S(2);
    // type of x is `&u32`
}

这种行为让我感到惊讶,因为左边的模式 似乎与右边的数据匹配,不像 let &S(x) = &S(2) & 排队。

看起来发生的事情是,当 RHS 是结构引用而 lhs 是具有字段模式的结构模式时,字段模式中变量的类型是 &F 其中 F 是字段的类型。

我要找的是:

我在 Rust 参考或 Rust 书中找不到任何关于此的内容,但我可能错过了。

您遇到的行为是在 Rust 1.26 中通过“匹配人体工程学”引入的,并在 its own RFC 中进行了描述。简而言之,在将引用与非引用模式进行匹配时,绑定模式默认切换为使用 ref 绑定。

在你的例子中,let S(x) = &S(2) 脱糖为 let &S(ref x) = &S(2)ref 的“遗留”状态在 Rust 书中不久 discussed

an explanation of what the behavior is that is general enough to explain what happens with tuples and enums in addition to structs. For example, in let (x,) = &(2,); the type of x is i32.

这是不正确的——如果你向 Rust 询问 x 的类型,它会告诉你它是 &i32,正如人们所期望的那样:

let (x,) = &(2i32,);
let () = x;
//       ^^   - this expression has type `&i32`

换句话说,适用于结构和枚举的相同绑定模式规则也适用于元组。