Skip to content

Improve Drop description (src/ch15-03-drop.md) #4181

@wowinter13

Description

@wowinter13

Hello guys!

TLDR: my main idea is to provide something more obvious than just println!("Dropping CustomSmartPointer with data {}!", self.data);. For instance, when we are talking about files, the current book chapter states that "...lets you customize what happens when a value is about to go out of scope.", but it doesn't really show any customization behavior. So I thought it might be helpful for newcomers to see that drop() could be useful when working with fixtures, so you don't need to write a function fn clear_data() and call it manually after every test - you can just extend drop behavior.

I thought about something like this + description:

use std::fs::File;
use std::path::PathBuf;

struct TempFile {
    file: File,
    path: PathBuf,
}

impl TempFile {
    fn new(path: PathBuf) -> std::io::Result<Self> {
        Ok(Self {
            file: File::create(&path)?,
            path,
        })
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        // Clean up the file when it's no longer needed
        if let Err(e) = std::fs::remove_file(&self.path) {
            eprintln!("Failed to remove temp file: {}", e);
        }
        println!("Dropped");
    }
}

fn main() -> std::io::Result<()> {
    let temp = TempFile::new("test.txt".into())?;
    
    // Work with temp.file here
    // The file will be automatically deleted when temp goes out of scope
    
    Ok(())
}

// OR

#[test]
fn test_with_temp_file() {
    let temp = TempFile::new("test.txt".into()).unwrap();
// print "Dropped"
}

What do you think? The example of course could be improved or changed, but what about the principal idea?

PS: I don't think this description belongs in the standard library docs (https://github.com/rust-lang/rust/blob/master/library/core/src/mem/mod.rs#L940) since this behavior is obvious, but I think it could be useful for The Rust Book.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions