以下代码能正常运行。
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32
}
fn area(shape: &Rectangle) -> u32 {
let Rectangle{width, height} = shape;
width * height
}
fn main() {
let rec1 = Rectangle {width: 5, height: 10};
println!("Area {}", area(&rec1));
println!("Rec {:?}", rec1);
}
将结构体&Shape
的引用替换为解引用引用*&Shape
也可以工作(例如:let Rectangle{width, height} = shape; --> let Rectangle{width, height} = *shape;
)。
我不知道为什么两个都能工作,难道在解构时有一些隐式的解引用操作吗?我认为&Shape
引用只是指向Shape
在内存中的位置,而*&Shape
是Shape
本身。width
和height
是struct Rectangle
的属性,而不是引用&Rectangle
。
let
也执行模式匹配,但只允许不可反驳的模式。代码确实对shape
进行了解构,这不是问题所在。 - Masklinn