WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Intermediate · question 35 of 100

Explain how the Drop trait works, and provide an example of when you would implement it.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

The Drop trait is a special trait in Rust that is used to define the code that should be run when an object goes out of scope. When an object is created in Rust, it is allocated on the stack or the heap, depending on how it is defined. The object is then used by the program until it goes out of scope. When the object goes out of scope, the Drop trait is used to clean up any resources used by the object before the memory is deallocated.

The Drop trait is defined in the standard library as:

    pub trait Drop {
        fn drop(&mut self);
    }

The ‘drop‘ method is called when an object goes out of scope, and it takes a mutable reference to ‘self‘. This allows the method to modify the object if necessary.

A common example of when to implement the ‘Drop‘ trait is when using a file handler that needs to be closed once an object goes out of scope. For example:

    use std::fs::File;
    
    struct MyFile {
        file: Option<File>,
    }
    
    impl MyFile {
        fn new(filename: &str) -> MyFile {
            let file = File::create(&filename).unwrap();
            MyFile { file: Some(file) }
        }
    }
    
    impl Drop for MyFile {
        fn drop(&mut self) {
            self.file.take().unwrap().close().unwrap();
        }
    }

In this example, we define a custom struct ‘MyFile‘ that wraps a ‘File‘ and implements the ‘Drop‘ trait. The ‘new‘ method creates the file and stores it in the ‘MyFile‘ struct. The ‘drop‘ method is called when the ‘MyFile‘ object goes out of scope, and it closes the file using the ‘close‘ method.

By implementing the ‘Drop‘ trait for ‘MyFile‘, we ensure that the file is always closed when the object goes out of scope, even if an error occurs.

In summary, the ‘Drop‘ trait is used to define the code that should be run when an object goes out of scope. It is commonly used to perform cleanup operations such as closing files, releasing memory or network resources.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics