3 The [`Drop`][Drop] trait only has one method: `drop`, which is called automatically
4 when an object goes out of scope. The main use of the `Drop` trait is to free the
5 resources that the implementor instance owns.
7 `Box`, `Vec`, `String`, `File`, and `Process` are some examples of types that
8 implement the `Drop` trait to free resources. The `Drop` trait can also be
9 manually implemented for any custom data type.
11 The following example adds a print to console to the `drop` function to announce
19 // This trivial implementation of `drop` adds a print to console.
20 impl Drop for Droppable {
22 println!("> Dropping {}", self.name);
27 let _a = Droppable { name: "a" };
31 let _b = Droppable { name: "b" };
35 let _c = Droppable { name: "c" };
36 let _d = Droppable { name: "d" };
38 println!("Exiting block B");
40 println!("Just exited block B");
42 println!("Exiting block A");
44 println!("Just exited block A");
46 // Variable can be manually dropped using the `drop` function
48 // TODO ^ Try commenting this line
50 println!("end of the main function");
52 // `_a` *won't* be `drop`ed again here, because it already has been
53 // (manually) `drop`ed
57 [Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html