实现说明
全部逻辑都在函数 drop、main中。
使用要点
- 跑完文件,输出里会留下标记——
drop:、holding:、slot released。 - 运行整个文件:
main会依次驱动drop。
常见问题
运行「重新赋值会立刻析构旧值」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 drop:、holding:、slot released 这类标签。
主要签名是 fn drop(&mut self)
核心语句
impl Drop for Tracked {
fn drop(&mut self) {
println!("drop: {}", self.label);
}
}
代码示例
struct Tracked {
label: &'static str,
}
impl Drop for Tracked {
fn drop(&mut self) {
println!("drop: {}", self.label);
}
}
fn main() {
let mut slot = Tracked { label: "first" };
println!("holding: {}", slot.label);
// reassignment drops the previous value right here, not at scope end
slot = Tracked { label: "second" };
println!("holding: {}", slot.label);
// explicit drop releases it early
drop(slot);
println!("slot released");
// shadowing instead keeps both values alive until the scope ends
let a = Tracked { label: "shadow-a" };
let a = Tracked { label: "shadow-b" };
println!("shadowed: {}", a.label);
}