]> git.proxmox.com Git - rustc.git/blame - src/doc/book/drop.md
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / doc / book / drop.md
CommitLineData
bd371182 1% Drop
9346a6ac 2
bd371182
AL
3Now that we’ve discussed traits, let’s talk about a particular trait provided
4by the Rust standard library, [`Drop`][drop]. The `Drop` trait provides a way
5to run some code when a value goes out of scope. For example:
6
7[drop]: ../std/ops/trait.Drop.html
8
9```rust
10struct HasDrop;
11
12impl Drop for HasDrop {
13 fn drop(&mut self) {
14 println!("Dropping!");
15 }
16}
17
18fn main() {
19 let x = HasDrop;
20
21 // do stuff
22
23} // x goes out of scope here
24```
25
26When `x` goes out of scope at the end of `main()`, the code for `Drop` will
27run. `Drop` has one method, which is also called `drop()`. It takes a mutable
28reference to `self`.
29
30That’s it! The mechanics of `Drop` are very simple, but there are some
31subtleties. For example, values are dropped in the opposite order they are
32declared. Here’s another example:
33
34```rust
35struct Firework {
36 strength: i32,
37}
38
39impl Drop for Firework {
40 fn drop(&mut self) {
41 println!("BOOM times {}!!!", self.strength);
42 }
43}
44
45fn main() {
46 let firecracker = Firework { strength: 1 };
47 let tnt = Firework { strength: 100 };
48}
49```
50
51This will output:
52
53```text
54BOOM times 100!!!
55BOOM times 1!!!
56```
57
54a0048b 58The `tnt` goes off before the `firecracker` does, because it was declared
bd371182
AL
59afterwards. Last in, first out.
60
61So what is `Drop` good for? Generally, `Drop` is used to clean up any resources
62associated with a `struct`. For example, the [`Arc<T>` type][arc] is a
63reference-counted type. When `Drop` is called, it will decrement the reference
64count, and if the total number of references is zero, will clean up the
65underlying value.
66
67[arc]: ../std/sync/struct.Arc.html