【发布时间】:2021-02-25 06:08:27
【问题描述】:
以下代码有效
#[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。
【问题讨论】:
-
你不是在制作一个新的 Rectangle(称为 rec1),它是 shape 的副本,而不是解构吗?如果你想解构你需要使用匹配,我认为。见Rust by Example。
-
@hkBst
let也执行模式匹配,但只允许 irrefutable 模式。代码确实解构了shape,这不是问题。
标签: rust