@@ -54,4 +54,56 @@ fn main() {
5454}
5555```
5656
57+ For a more practical example, here's how the ` Drop ` trait can be used to automatically
58+ clean up temporary files when they're no longer needed:
59+
60+ ``` rust,editable
61+ use std::fs::File;
62+ use std::path::PathBuf;
63+
64+ struct TempFile {
65+ file: File,
66+ path: PathBuf,
67+ }
68+
69+ impl TempFile {
70+ fn new(path: PathBuf) -> std::io::Result<Self> {
71+ // Note: File::create() will overwrite existing files
72+ let file = File::create(&path)?;
73+
74+ Ok(Self { file, path })
75+ }
76+ }
77+
78+ // When TempFile is dropped:
79+ // 1. First, the File will be automatically closed (Drop for File)
80+ // 2. Then our drop implementation will remove the file
81+ impl Drop for TempFile {
82+ fn drop(&mut self) {
83+ // Note: File is already closed at this point
84+ if let Err(e) = std::fs::remove_file(&self.path) {
85+ eprintln!("Failed to remove temporary file: {}", e);
86+ }
87+ println!("> Dropped temporary file: {:?}", self.path);
88+ }
89+ }
90+
91+ fn main() -> std::io::Result<()> {
92+ // Create a new scope to demonstrate drop behavior
93+ {
94+ let temp = TempFile::new("test.txt".into())?;
95+ println!("Temporary file created");
96+ // File will be automatically cleaned up when temp goes out of scope
97+ }
98+ println!("End of scope - file should be cleaned up");
99+
100+ // We can also manually drop if needed
101+ let temp2 = TempFile::new("another_test.txt".into())?;
102+ drop(temp2); // Explicitly drop the file
103+ println!("Manually dropped file");
104+
105+ Ok(())
106+ }
107+ ```
108+
57109[ Drop ] : https://doc.rust-lang.org/std/ops/trait.Drop.html
0 commit comments