做这个练习时https://github.com/rust-lang/rustlings/blob/main/exercises/option/option3.rs,我发现了
ref
关键字,并且我很困惑在模式匹配中何时应该使用&
或ref
。在这个例子中,每个匹配都输出相同的消息,但我无法确定它们之间的区别:struct Point { x: i32, y: i32}
fn main() {
let y: Option<Point> = Some(Point { x: 100, y: 200 });
match &y {
Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => println!("no match"),
}
match y {
Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => println!("no match"),
}
match &y {
Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
_ => println!("no match"),
}
y;
}