]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/trait/drop.md
New upstream version 1.25.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / trait / drop.md
1 # Drop
2
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.
6
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.
10
11 The following example adds a print to console to the `drop` function to announce
12 when it is called.
13
14 ```rust,editable
15 struct Droppable {
16 name: &'static str,
17 }
18
19 // This trivial implementation of `drop` adds a print to console.
20 impl Drop for Droppable {
21 fn drop(&mut self) {
22 println!("> Dropping {}", self.name);
23 }
24 }
25
26 fn main() {
27 let _a = Droppable { name: "a" };
28
29 // block A
30 {
31 let _b = Droppable { name: "b" };
32
33 // block B
34 {
35 let _c = Droppable { name: "c" };
36 let _d = Droppable { name: "d" };
37
38 println!("Exiting block B");
39 }
40 println!("Just exited block B");
41
42 println!("Exiting block A");
43 }
44 println!("Just exited block A");
45
46 // Variable can be manually dropped using the `drop` function
47 drop(_a);
48 // TODO ^ Try commenting this line
49
50 println!("end of the main function");
51
52 // `_a` *won't* be `drop`ed again here, because it already has been
53 // (manually) `drop`ed
54 }
55 ```
56
57 [Drop]: https://doc.rust-lang.org/std/ops/trait.Drop.html