实现说明
逻辑集中在函数 new、drop、main里。
使用要点
- 每一步打印都带着自己的标签:
created、cleaned up、using。 main按顺序串起new、drop;运行文件就会把这个流程跑一遍。
常见问题
运行「实现 Drop 在作用域结束清理」会打印什么?
整个文件跑完,输出行以 created、cleaned up、using 这类前缀开头。
入口签名:fn new(path: &str) -> Self
核心语句
fn new(path: &str) -> Self {
println!("created {path}");
Self { path: path.to_string() }
}
impl Drop for TempFile {
// 值离开作用域时编译器自动插入的清理点,无需手动调用
fn drop(&mut self) {
println!("cleaned up {}", self.path);
}
}
代码示例
struct TempFile {
path: String,
}
impl TempFile {
fn new(path: &str) -> Self {
println!("created {path}");
Self { path: path.to_string() }
}
}
impl Drop for TempFile {
// 值离开作用域时编译器自动插入的清理点,无需手动调用
fn drop(&mut self) {
println!("cleaned up {}", self.path);
}
}
fn main() {
{
let guard = TempFile::new("cache/session.tmp");
println!("using {}", guard.path);
} // guard 在块结束处 drop
println!("scope ended");
let leaked = TempFile::new("cache/leaked.tmp");
drop(leaked); // 也可以用 drop 函数提前显式释放
println!("explicit drop done");
}