|
| 1 | +--- |
| 2 | +minutes: 30 |
| 3 | +--- |
| 4 | + |
| 5 | +# RAII and `Drop` in Practice |
| 6 | + |
| 7 | +RAII (*Resource Acquisition Is Initialization*) |
| 8 | +means tying the lifetime of a resource to the lifetime of a value. |
| 9 | + |
| 10 | +Rust applies RAII automatically for memory management. |
| 11 | +The `Drop` trait lets you extend this pattern to anything else. |
| 12 | + |
| 13 | +```rust |
| 14 | +use std::sync::Mutex; |
| 15 | + |
| 16 | +fn main() { |
| 17 | + let mux = Mutex::new(vec![1, 2, 3]); |
| 18 | + |
| 19 | + { |
| 20 | + let mut data = mux.lock().unwrap(); |
| 21 | + data.push(4); // lock held here |
| 22 | + } // lock automatically released here |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +<details> |
| 27 | + |
| 28 | +- In the above example |
| 29 | + [the `Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) |
| 30 | + owns its data: you can’t access the value inside without first acquiring the lock. |
| 31 | + |
| 32 | + `mux.lock()` returns a |
| 33 | + [`MutexGuard`](https://doc.rust-lang.org/std/sync/struct.MutexGuard.html), |
| 34 | + which [dereferences](https://doc.rust-lang.org/std/ops/trait.DerefMut.html) |
| 35 | + to the data and implements [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html). |
| 36 | + |
| 37 | +- You may recall from [the Memory Management chapter](../../memory-management/drop.md) |
| 38 | + that the [`Drop` trait](https://doc.rust-lang.org/std/ops/trait.Drop.html) |
| 39 | + lets you define what should happen when a resource is dropped. |
| 40 | + |
| 41 | + - In [the Blocks and Scopes chapter](../../control-flow-basics/blocks-and-scopes.md), |
| 42 | + we saw the most common situation where a resource is dropped: |
| 43 | + when the scope of its _owner_ ends at the boundary of a block (`{}`). |
| 44 | + |
| 45 | + - The use of |
| 46 | + [`std::mem::drop(val)`](https://doc.rust-lang.org/std/mem/fn.drop.html) |
| 47 | + allows you to _move_ a value out of scope before the block ends. |
| 48 | + |
| 49 | + - There are also other scenarios where this can happen, |
| 50 | + such as when the value owning the resource is "shadowed" by another value: |
| 51 | + |
| 52 | + ```rust |
| 53 | + let a = String::from("foo"); |
| 54 | + let a = 3; // ^ The previous string is dropped here |
| 55 | + // because we shadow its binding with a new value. |
| 56 | + ``` |
| 57 | + |
| 58 | + - Recall also from [the Drop chapter](../../memory-management/drop.md) |
| 59 | + that for a composite type such as a `struct`, all its fields will be dropped |
| 60 | + when the struct itself is dropped. |
| 61 | + If a field implements the `Drop` trait, its `Drop::drop` |
| 62 | + _trait_ method will also be invoked. |
| 63 | + |
| 64 | +- In any scenario where the stack unwinds the value, it is guaranteed |
| 65 | + that the [`Drop::drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html#tymethod.drop) |
| 66 | + method of a value `a` will be called. |
| 67 | + |
| 68 | + - This holds true for happy paths such as: |
| 69 | + |
| 70 | + - Exiting a block or function scope. |
| 71 | + |
| 72 | + - Returning early with an explicit `return` statement, |
| 73 | + or implicitly by using |
| 74 | + [the Try operator (`?`)](../../error-handling/try.md) |
| 75 | + to early-return `Option` or `Result` values. |
| 76 | + |
| 77 | + - It also holds for unexpected scenarios where a `panic` is triggered, if: |
| 78 | + |
| 79 | + - The stack unwinds on panic (which is the default), |
| 80 | + allowing for graceful cleanup of resources. |
| 81 | + |
| 82 | + This unwind behavior can be overridden to instead |
| 83 | + [abort on panic](https://github.com/rust-lang/rust/blob/master/library/panic_abort/src/lib.rs). |
| 84 | + |
| 85 | + - No panic occurs within any of the `drop` methods |
| 86 | + invoked before reaching the `drop` call of the object `a`. |
| 87 | + |
| 88 | + - Note that |
| 89 | + [an explicit exit of the program](https://doc.rust-lang.org/std/process/fn.exit.html), |
| 90 | + as sometimes used in CLI tools, terminates the process immediately. |
| 91 | + In other words, the stack is not unwound in this case, |
| 92 | + and the `drop` method will not be called. |
| 93 | + |
| 94 | +- `Drop` is a great fit for use cases like `Mutex`. |
| 95 | + |
| 96 | + When the guard goes out of scope, [`Drop::drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html#tymethod.drop) |
| 97 | + is called and unlocks the mutex automatically. |
| 98 | + |
| 99 | + In contrast to C++ or Java, where you often have to unlock manually |
| 100 | + or use a `lock/unlock` pattern, Rust ensures the |
| 101 | + lock *cannot* be forgotten, thanks to the compiler. |
| 102 | + |
| 103 | +- In other scenarios, the `Drop` trait shows its limitations. |
| 104 | + Next, we'll look at what those are and how we can |
| 105 | + address them. |
| 106 | + |
| 107 | +## More to explore |
| 108 | + |
| 109 | +To learn more about building synchronization primitives, |
| 110 | +consider reading [*Rust Atomics and Locks* by Mara Bos](https://marabos.nl/atomics/). |
| 111 | + |
| 112 | +The book demonstrates, among other topics, how `Drop` |
| 113 | +and RAII work together in constructs like `Mutex`. |
| 114 | + |
| 115 | + |
| 116 | +</details> |
0 commit comments