Cleanup follows scope
Rust calls a type’s Drop implementation when a value goes out of scope. That method can release a resource, such as a file handle or a lock. In the Rust Book’s example, two values are created in sequence. Their cleanup messages appear in reverse order: the second value is dropped first. A later statement in the same scope runs before this automatic cleanup.
This reverse order applies to local variables. Struct fields drop in declaration order, as the Drop trait documentation specifies. The local order matters when a resource has work to do at the end of its lifetime. You can rely on scope exit for routine cleanup. You can also choose an earlier end to the lifetime when work no longer needs the resource. The key is to identify which value holds it. For a mutex lock, that value is the guard.
The guard decides when the lock opens
A MutexGuard unlocks its mutex when it is dropped. Holding the guard through unrelated work therefore keeps the mutex locked through that work. To end that hold sooner, pass the guard to std::mem::drop. The function takes ownership of its argument; the guard is dropped before the call returns.
use std::sync::Mutex;
fn main() {
let counter = Mutex::new(0);
let mut guard = counter.lock().unwrap();
*guard += 1;
drop(guard); // Unlock before the next operation.
let current = *counter.lock().unwrap();
println!("{current}");
}
The first guard protects the increment. drop(guard) releases its lock before the second lock call. The second lock creates a new guard for the read. The first guard cannot be used again after it has been moved into drop. Rust’s explanation of early cleanup uses this pattern for locks: release one while the surrounding scope continues.
What to do
First, find the variable that holds the resource you want to release. Check whether later statements still need access through that variable. If they do, keep it alive until those uses finish. If they do not, put the resource work in a smaller scope or call drop(guard) immediately after its last use. Prefer the smaller scope when it makes the lifetime clear. Use the explicit call when the surrounding scope needs to continue and the release point deserves attention. Do not call the Drop trait method directly: the Rust Book shows that Rust rejects it.

The Campfire
No commentsNobody has pulled up a log by this one yet. Be the first to say what you make of it.
Held for the desk. It appears after a look.