core/ops/drop.rs
1/// Custom code within the destructor.
2///
3/// When a value is no longer needed, Rust will run a "destructor" on that value.
4/// The most common way that a value is no longer needed is when it goes out of
5/// scope. Destructors may still run in other circumstances, but we're going to
6/// focus on scope for the examples here. To learn about some of those other cases,
7/// please see [the reference] section on destructors.
8///
9/// [the reference]: https://doc.rust-lang.org/reference/destructors.html
10///
11/// This destructor consists of two components:
12/// - A call to `Drop::drop` for that value, if this special `Drop` trait is implemented for its type.
13/// - The automatically generated "drop glue" which recursively calls the destructors
14/// of all the fields of this value.
15///
16/// As Rust automatically calls the destructors of all contained fields,
17/// you don't have to implement `Drop` in most cases. But there are some cases where
18/// it is useful, for example for types which directly manage a resource.
19/// That resource may be memory, it may be a file descriptor, it may be a network socket.
20/// Once a value of that type is no longer going to be used, it should "clean up" its
21/// resource by freeing the memory or closing the file or socket. This is
22/// the job of a destructor, and therefore the job of `Drop::drop`.
23///
24/// ## Examples
25///
26/// To see destructors in action, let's take a look at the following program:
27///
28/// ```rust
29/// struct HasDrop;
30///
31/// impl Drop for HasDrop {
32/// fn drop(&mut self) {
33/// println!("Dropping HasDrop!");
34/// }
35/// }