Rust has no garbage collector (GC). Every value has one owner, and the value is dropped where the owner goes out of scope. The runtime does not pick that point; you can read it from the scopes in the source code.
When I built servers in GC languages, I left memory to the runtime and handled resources that must be closed promptly, such as files and connections, separately with Java’s try-with-resources, Python’s with, or Go’s defer. Rust handles both with one rule, and I wanted to pin down exactly what that rule runs, and when. Every example below was compiled and run with rustc 1.94.1, edition 2021.
Owners and scopes
A String allocates its text on the heap.
fn main() {
{
let greeting = String::from("hello");
println!("{greeting}");
} // greeting goes out of scope and its heap buffer is freed
}
greeting owns this String. When the inner block ends, so does the scope of greeting, and the drop the compiler inserted at that point runs and frees the heap buffer. The Rust Programming Language states the rules in three sentences.
- Each value has an owner
- There can only be one owner at a time
- When the owner goes out of scope, the value is dropped
Because there is only one owner, there is exactly one point where each value is dropped. Safe code never frees the same buffer twice.
The Drop trait
Code that runs when a value is dropped is defined with the Drop trait. Vec and String free their heap buffers when dropped, and a type you write can run its own code at the same moment by implementing Drop. The examples below use a Connection type that prints its name when it is dropped.
struct Connection {
name: &'static str,
}
impl Drop for Connection {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
You cannot call the drop method yourself.
fn main() {
let conn = Connection { name: "conn" };
conn.drop();
}
error[E0040]: explicit use of destructor method
--> explicit.rs:13:10
|
13 | conn.drop();
| ^^^^ explicit destructor calls not allowed
|
help: consider using `drop` function
|
13 - conn.drop();
13 + drop(conn);
|
If explicit calls were allowed, they would collide with the automatic drop at the end of the scope and drop the same value twice. The drop(conn) the compiler suggests is std::mem::drop, which is in the prelude. It takes ownership of its argument and does nothing. When the function returns, its parameter goes out of scope, and Drop::drop runs there.
fn main() {
let conn = Connection { name: "conn" };
drop(conn); // std::mem::drop
println!("end of main");
}
drop conn
end of main
Drop order
When a scope holds several values, the order they are dropped in is fixed. I printed it with two variables, an inner block, and a struct with two Connection fields.
// Connection is the same as above
struct Session {
conn: Connection,
cache: Connection,
}
fn main() {
let _first = Connection { name: "first" };
let _second = Connection { name: "second" };
{
let _inner = Connection { name: "inner" };
println!("end of inner scope");
}
let _session = Session {
conn: Connection { name: "session.conn" },
cache: Connection { name: "session.cache" },
};
println!("end of main");
}
end of inner scope
drop inner
end of main
drop session.conn
drop session.cache
drop second
drop first
The inner block ends first, so _inner is dropped first. When main ends, the remaining variables are dropped in reverse order of declaration: _session, declared last, goes first and _first goes last. Inside _session, the fields are dropped in declaration order, conn then cache. The Rust Reference defines variables as dropped in reverse declaration order and struct fields in declaration order. The Drop docs say the language guarantees this order.
A leading _ on a variable name only silences the unused-variable warning. _first is dropped at the end of its scope like any other variable. A pattern that is just _ behaves differently.
Moved values
Passing a value as a function argument moves ownership to the function’s parameter.
// Connection is the same as above
fn close(conn: Connection) {
println!("close {}", conn.name);
} // the new owner, conn, goes out of scope here
fn main() {
let _kept = Connection { name: "kept" };
let handed = Connection { name: "handed" };
close(handed); // ownership moves into close
println!("end of main");
}
close handed
drop handed
end of main
drop kept
handed was dropped at the end of close, not at the end of main. When the owner changes, the drop point follows it to the end of the new owner’s scope. When main ends, handed no longer holds a value, so only _kept is dropped. The Reference treats a variable that has been moved out of as uninitialized, and an uninitialized variable is not dropped. Dropping a moved value too would drop it twice.
Resources other than memory
Drop is not only for freeing memory. Keeping a resource only for as long as the value that owns it exists, and cleaning it up when that value is dropped, is called RAII (Resource Acquisition Is Initialization). The name comes from C++, and files and locks in the standard library work this way.
std::fs::File closes the file when it is dropped.
use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
{
let mut log = File::create("app.log")?;
log.write_all(b"started\n")?;
log.sync_all()?; // get disk write errors before the drop
} // log is dropped and the file is closed
println!("{}", std::fs::read_to_string("app.log")?);
Ok(())
}
The Drop implementation of File ignores errors raised while closing. drop returns nothing, so it cannot pass them on. The File docs point to sync_all when those errors must be handled. sync_all waits until the data reaches the disk and returns any error from that step as a Result.
Mutex::lock returns a MutexGuard, and the lock is released when the guard is dropped. I checked the lock state with try_lock while the guard was alive and after its scope ended.
use std::sync::Mutex;
fn main() {
let counter = Mutex::new(0);
{
let mut guard = counter.lock().unwrap();
*guard += 1;
println!("in scope: locked = {}", counter.try_lock().is_err());
} // guard is dropped and the lock is released
println!("after scope: locked = {}", counter.try_lock().is_err());
}
in scope: locked = true
after scope: locked = false
try_lock does not wait on a locked mutex; it returns a WouldBlock error. If the thread that owns the guard calls lock again, the docs leave the behavior unspecified. They only say it might panic or deadlock, so the example checks the state with try_lock instead.
Nothing in the code calls unlock. The lock stays held until the guard’s scope ends. To release it earlier, narrow the scope with an inner block or call drop(guard).
If the guard is never stored in a variable, the lock is released right away. The _ pattern binds the value to nothing. A value with no owner stays a temporary, and per the Reference it is dropped at the end of the statement. rustc rejects this mistake for locks by default.
let _ = counter.lock().unwrap();
error: non-binding let on a synchronization lock
--> underscore.rs:6:9
|
6 | let _ = counter.lock().unwrap();
| ^ this lock is not assigned to a binding and is immediately dropped
|
= note: `#[deny(let_underscore_lock)]` (part of `#[deny(let_underscore)]`) on by default
help: consider binding to an unused variable to avoid immediately dropping the value
|
6 | let _unused = counter.lock().unwrap();
| ++++++
The let_underscore_lock lint covers only lock guards. Other types are dropped at the end of the statement without any warning under the default settings.
// Connection is the same as above
fn main() {
let _ = Connection { name: "wildcard" };
let _named = Connection { name: "named" };
println!("end of main");
}
drop wildcard
end of main
drop named
When drop does not run
Values are not always dropped.
// Connection is the same as above
fn main() {
let forgotten = Connection { name: "forgotten" };
std::mem::forget(forgotten);
let _conn = Connection { name: "conn" };
std::process::exit(0);
}
This program prints nothing. std::mem::forget takes ownership of a value and never runs its destructor. std::process::exit ends the process without dropping the values left on any thread’s stack.
The docs give the reason forget is not unsafe: Rust’s safety guarantees do not include a promise that destructors always run. I concluded that drop is best treated as a guarantee of cleanup on the normal path. For a record that must survive however the process ends, I judged it better not to rely on drop alone.
Wrapping up
Rust gives every value one owner and drops the value where that owner’s scope ends. Variables are dropped in reverse declaration order, fields in declaration order, and a moved value is dropped once, at the end of its new owner’s scope. The same rule applies to heap buffers, files, and mutex locks, so on the normal path there is no separate release code to write. Explicit handling is needed only when close errors matter or when a path such as forget or exit skips the drop. In a GC language, the runtime decides when memory is reclaimed, and other resources are released separately with defer or with. In Rust, both follow the owner’s scope.
References
- Three Garbage Collectors — How Java, Python, and Go Reclaim Memory: how a GC decides the point of release at run time
- Rust Lifetimes: how a borrow held by a value that implements
Droplasts until the drop at the end of the scope - rust-server: using
Dropto shut down a thread pool’s worker threads - The Rust Programming Language — What is Ownership?
- The Rust Programming Language — Running Code on Cleanup with the Drop Trait
- The Rust Reference — Destructors
std::ops::Dropstd::sync::MutexGuardstd::mem::forget