Drop

The Drop trait only has one method: drop, which is called automatically
when an object goes out of scope. The main use of the Drop trait is to free the
resources that the implementor instance owns.

Box, Vec, String, File, and Process are some examples of types that
implement the Drop trait to free resources. The Drop trait can also be
manually implemented for any custom data type.

The following example adds a print to console to the drop function to announce
when it is called.

  1. struct Droppable {
  2. name: &'static str,
  3. }
  4. // This trivial implementation of `drop` adds a print to console.
  5. impl Drop for Droppable {
  6. fn drop(&mut self) {
  7. println!("> Dropping {}", self.name);
  8. }
  9. }
  10. fn main() {
  11. let _a = Droppable { name: "a" };
  12. // block A
  13. {
  14. let _b = Droppable { name: "b" };
  15. // block B
  16. {
  17. let _c = Droppable { name: "c" };
  18. let _d = Droppable { name: "d" };
  19. println!("Exiting block B");
  20. }
  21. println!("Just exited block B");
  22. println!("Exiting block A");
  23. }
  24. println!("Just exited block A");
  25. // Variable can be manually dropped using the `drop` function
  26. drop(_a);
  27. // TODO ^ Try commenting this line
  28. println!("end of the main function");
  29. // `_a` *won't* be `drop`ed again here, because it already has been
  30. // (manually) `drop`ed
  31. }