考虑以下代码
fn main() {
let s = (&&0,);
let (x,) = s; // &&i32
let (&y,) = s; // &i32
let (&&z,) = s; // i32
let t = &(&0,);
let (x,) = t; // &&i32
let (&y,) = t; // i32
let u = &&(0,);
let (x,) = u; // &i32
let (&y,) = u; // mismatched types expected type `{integer}` found reference `&_`
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下,为什么&模式在每种情况下表现不同?我想它以某种方式与人体工程学相匹配,也许一些强制起作用了?但我无法理解它。
当对引用与不包含引用的模式进行模式匹配时会发生什么?
这是使用结构模式的示例:
fn main() {
struct S(u32);
let S(x) = &S(2);
// type of x is `&u32`
}
Run Code Online (Sandbox Code Playgroud)
这种行为令我感到惊讶,因为左侧的模式似乎与右侧的数据不匹配,这与s 排列的let &S(x) = &S(2)位置不同。&
看起来发生的情况是,当 RHS 是结构引用并且 lhs 是具有字段模式的结构模式时,字段模式中变量的类型就是&FwhereF是字段的类型。
我正在寻找的是:
let (x,) = &(2,);类型x为i32(更正:) &i32。我在《Rust Reference》或《Rust Book》中找不到任何有关此内容的信息,但我可能错过了。
我在阅读这篇文章时遇到了这种奇怪的行为,这篇文章的核心问题是当你匹配时(&k, &v) = &(&String, &String),k会v得到类型String。
为了弄清楚发生了什么,我编写了以下测试代码,结果让我更加震惊和困惑:
fn main() {
let x: &(&String, &String) = &(&String::new(), &String::new());
let ref_to_x: &&(&String, &String) = &x;
let ref_ref_to_x: &&&(&String, &String) = &&x;
let ref_ref_ref_to_x: &&&&(&String, &String) = &&&x;
// code snippet 1
let (a, b) = x; // type of a: &&String, type of b: &&String
let (a, b) = ref_to_x; // type of a: &&String, type of b: &&String
let (a, …Run Code Online (Sandbox Code Playgroud)