|
1 |
| -% `Drop` |
| 1 | +% Drop |
2 | 2 |
|
3 |
| -Coming soon! |
| 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: |
| 6 | + |
| 7 | +[drop]: ../std/ops/trait.Drop.html |
| 8 | + |
| 9 | +```rust |
| 10 | +struct HasDrop; |
| 11 | + |
| 12 | +impl Drop for HasDrop { |
| 13 | + fn drop(&mut self) { |
| 14 | + println!("Dropping!"); |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +fn main() { |
| 19 | + let x = HasDrop; |
| 20 | + |
| 21 | + // do stuff |
| 22 | + |
| 23 | +} // x goes out of scope here |
| 24 | +``` |
| 25 | + |
| 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 |
| 28 | +reference to `self`. |
| 29 | + |
| 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: |
| 33 | + |
| 34 | +```rust |
| 35 | +struct Firework { |
| 36 | + strength: i32, |
| 37 | +} |
| 38 | + |
| 39 | +impl Drop for Firework { |
| 40 | + fn drop(&mut self) { |
| 41 | + println!("BOOM times {}!!!", self.strength); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +fn main() { |
| 46 | + let firecracker = Firework { strength: 1 }; |
| 47 | + let tnt = Firework { strength: 100 }; |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +This will output: |
| 52 | + |
| 53 | +```text |
| 54 | +BOOM times 100!!! |
| 55 | +BOOM times 1!!! |
| 56 | +``` |
| 57 | + |
| 58 | +The TNT goes off before the firecracker does, because it was declared |
| 59 | +afterwards. Last in, first out. |
| 60 | + |
| 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 |
| 65 | +underlying value. |
| 66 | + |
| 67 | +[arc]: ../std/sync/struct.Arc.html |
0 commit comments