我有这段代码:
fn main() {
let x = Some(1);
let y = Some(2);
println!("{}",matches!(x,y));
println!("{}",matches!(x,Some(2)));
}
打印
true
和 false
我希望它两次返回 false,因为 Some
的值不同。这种行为背后的原因是什么?你是否在幕后不知何故被遮蔽了?
这种行为背后的原因是什么?你是否在幕后不知何故被遮蔽了?
是的,这引入了一个新的绑定
y
,它将匹配任何内容。此代码会生成警告,表明 y
均未使用:
warning: unused variable: `y`
--> src/main.rs:3:9
|
3 | let y = Some(2);
| ^ help: if this is intentional, prefix it with an underscore: `_y`
|
= note: `#[warn(unused_variables)]` on by default
warning: unused variable: `y`
--> src/main.rs:4:30
|
4 | println!("{}",matches!(x,y));
| ^ help: if this is intentional, prefix it with an underscore: `_y`
这类似于为什么使用非文字模式时无法访问此匹配模式?但形式略有不同。这里,
matches!(x,y)
相当于这个(matches!
参见source):
match x {
y => true,
_ => false,
}
标识符用于在模式中创建新的绑定(除非它们是常量),因此不要使用具有该名称的变量。