3 Now that we’ve discussed traits, let’s talk about a particular trait provided
4 by the Rust standard library, [`Drop`][drop]. The `Drop` trait provides a way
5 to run some code when a value goes out of scope. For example:
7 [drop]: ../std/ops/trait.Drop.html
12 impl Drop for HasDrop {
14 println!("Dropping!");
23 } // x goes out of scope here
26 When `x` goes out of scope at the end of `main()`, the code for `Drop` will
27 run. `Drop` has one method, which is also called `drop()`. It takes a mutable
30 That’s it! The mechanics of `Drop` are very simple, but there are some
31 subtleties. For example, values are dropped in the opposite order they are
32 declared. Here’s another example:
39 impl Drop for Firework {
41 println!("BOOM times {}!!!", self.strength);
46 let firecracker = Firework { strength: 1 };
47 let tnt = Firework { strength: 100 };
58 The `tnt` goes off before the `firecracker` does, because it was declared
59 afterwards. Last in, first out.
61 So what is `Drop` good for? Generally, `Drop` is used to clean up any resources
62 associated with a `struct`. For example, the [`Arc<T>` type][arc] is a
63 reference-counted type. When `Drop` is called, it will decrement the reference
64 count, and if the total number of references is zero, will clean up the
67 [arc]: ../std/sync/struct.Arc.html