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. }
  4. impl Drop for Droppable {
  5. fn drop(&mut self) {
  6. println!("Dropping {}", self.name);
  7. }
  8. }
  9. fn main() {
  10. let a = Droppable { name: "a" };
  11. {
  12. let b = Droppable { name: "b" };
  13. {
  14. let c = Droppable { name: "c" };
  15. let d = Droppable { name: "d" };
  16. println!("Exiting block B");
  17. }
  18. println!("Exiting block A");
  19. }
  20. drop(a);
  21. println!("Exiting main");
  22. }

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().