Drop

Drop trait 只有一个方法:drop,它会在对象离开作用域时自动调用。Drop trait 的主要用途是释放实现该 trait 的实例所拥有的资源。

BoxVecStringFileProcess 是一些实现了 Drop trait 以释放资源的类型示例。你也可以为任何自定义数据类型手动实现 Drop trait。

下面的例子在 drop 函数中添加了一个控制台打印,用于宣告它被调用的时机。

For a more practical example, here's how the Drop trait can be used to automatically clean up temporary files when they're no longer needed:

use std::fs::File; use std::path::PathBuf; struct TempFile { file: File, path: PathBuf, } impl TempFile { fn new(path: PathBuf) -> std::io::Result<Self> { // Note: File::create() will overwrite existing files let file = File::create(&path)?; Ok(Self { file, path }) } } // When TempFile is dropped: // 1. First, the File will be automatically closed (Drop for File) // 2. Then our drop implementation will remove the file impl Drop for TempFile { fn drop(&mut self) { // Note: File is already closed at this point if let Err(e) = std::fs::remove_file(&self.path) { eprintln!("Failed to remove temporary file: {}", e); } println!("> Dropped temporary file: {:?}", self.path); } } fn main() -> std::io::Result<()> { // Create a new scope to demonstrate drop behavior { let temp = TempFile::new("test.txt".into())?; println!("Temporary file created"); // File will be automatically cleaned up when temp goes out of scope } println!("End of scope - file should be cleaned up"); // We can also manually drop if needed let temp2 = TempFile::new("another_test.txt".into())?; drop(temp2); // Explicitly drop the file println!("Manually dropped file"); Ok(()) }