The Drop
Trait
Values which implement Drop
can specify code to run when they go out of scope:
struct Droppable { name: &'static str, } impl Drop for Droppable { fn drop(&mut self) { println!("Dropping {}", self.name); } } fn main() { let a = Droppable { name: "a" }; { let b = Droppable { name: "b" }; { let c = Droppable { name: "c" }; let d = Droppable { name: "d" }; println!("Exiting block B"); } println!("Exiting block A"); } drop(a); println!("Exiting main"); }
Discussion points:
- Why does not
Drop::drop
takeself
?- Short-answer: If it did,
std::mem::drop
would be called at the end of the block, resulting in another call toDrop::drop
, and a stack overflow!
- Short-answer: If it did,
- Try replacing
drop(a)
witha.drop()
.