The Drop Trait

Values which implement Drop can specify code to run when they go out of scope:

1. struct Droppable {
2. name: &'static str,
3. }

5. impl Drop for Droppable {
6. fn drop(&mut self) {
7. println!("Dropping {}", self.name);
8. }
9. }

11. fn main() {
12. let a = Droppable { name: "a" };
13. {
14. let b = Droppable { name: "b" };
15. {
16. let c = Droppable { name: "c" };
17. let d = Droppable { name: "d" };
18. println!("Exiting block B");
19. }
20. println!("Exiting block A");
21. }
22. drop(a);
23. println!("Exiting main");
24. }

Discussion points:

  • Why does not Drop::drop take self?
  • Short-answer: If it did, std::mem::drop would be called at the end of the block, resulting in another call to Drop::drop, and a stack overflow!
  • Try replacing drop(a) with a.drop().