简体   繁体   English

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

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

What happens when pattern-matching against a reference with a pattern that doesn't include a reference?当使用不包含引用的模式对引用进行模式匹配时会发生什么?

Here's an example using a struct pattern:这是一个使用结构模式的示例:

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

The behavior is surprising to me because the pattern on the left does not seem to match the data on the right, unlike let &S(x) = &S(2) where the & s line up.这种行为让我感到惊讶,因为左侧的模式似乎与右侧的数据匹配,这与let &S(x) = &S(2)& s 排列不同。

It looks like what is happening is that when the RHS is a struct reference and the lhs is a struct pattern with field patterns, the type of the variable in the field pattern is &F where F is the type of the field.看起来正在发生的事情是,当 RHS 是结构引用并且 lhs 是具有字段模式的结构模式时,字段模式中变量的类型是&F ,其中F是字段的类型。

What I am looking for is:我正在寻找的是:

  • a reference that explains what the expected behavior is解释预期行为的参考
  • 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,);例如,在let (x,) = &(2,); the type of x is i32 ( correction : &i32 ). x的类型是i32更正&i32 )。

I couldn't find anything about this in the Rust Reference or the Rust Book, but I may have missed it.我在 Rust 参考或 Rust 书中找不到任何关于此的信息,但我可能错过了。

The behavior you encountered was introduced with "match ergonomics" in Rust 1.26 and is described in its own RFC .您遇到的行为是在 Rust 1.26 中通过“匹配人体工程学”引入的,并在其自己的 RFC中进行了描述。 In short, when matching references against non-reference patterns, the binding mode is switched to use ref binding by default.简而言之,在将引用与非引用模式匹配时,默认情况下将绑定模式切换为使用ref绑定。

In your case, let S(x) = &S(2) desugars to let &S(ref x) = &S(2) .在你的情况下, let S(x) = &S(2)去糖let &S(ref x) = &S(2) The "legacy" status of ref is shortly discussed in the Rust book. Rust 书中简要讨论ref的“遗留”状态。

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,);例如,在let (x,) = &(2,); the type of x is i32 . x的类型是i32

This is incorrect - if you ask Rust for the type of x , it will tell you it is &i32 , as one would expect:这是不正确的——如果您向 Rust 询问x的类型,它会告诉您它是&i32 ,正如人们所期望的那样:

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

In other words, the same binding-mode rules that apply to structs and enums also apply to tuples.换句话说,适用于结构和枚举的相同绑定模式规则也适用于元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM