Skip to content

Add more examples @ drop.md #1912

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/trait/drop.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,56 @@ fn main() {
}
```

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:

```rust,editable
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(())
}
```

[Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html