Answer#
In C# you wrap a resource in using and in Java in try (...), because the garbage collector will free the memory eventually but will not close the file or the connection at a predictable time. In Rust the owner of a value decides when it dies: at the closing brace of its scope, or earlier if it is moved or passed to drop. A type that holds a resource implements the Drop trait, and its drop method runs at that moment. The standard types you use (File, TcpStream, MutexGuard, Vec) already do.
The three programs below do the same thing: open resource a, open b, then either finish normally or fail. All three were run (the Java and C# listings are excerpts; each program also calls work once normally and once failing, and catches the exception); the output is the same order of events.
Java (OpenJDK 17.0.18):
public class Res implements AutoCloseable {
final String name;
Res(String n) { name = n; System.out.println("open " + n); }
public void close() { System.out.println("close " + name); }
static void work(boolean fail) throws Exception {
try (Res a = new Res("a"); Res b = new Res("b")) {
if (fail) throw new Exception("failed");
System.out.println("body done");
}
}
}C# (.NET SDK 10.0.302):
static void Work(bool fail)
{
using var a = new Res("a");
using var b = new Res("b");
if (fail) throw new Exception("failed");
Console.WriteLine("body done");
}
class Res : IDisposable
{
readonly string name;
public Res(string n) { name = n; Console.WriteLine($"open {n}"); }
public void Dispose() => Console.WriteLine($"close {name}");
}Rust (rustc 1.93.0), where nothing marks the scope except the variables themselves:
struct Res(&'static str);
impl Res {
fn open(name: &'static str) -> Res {
println!("open {name}");
Res(name)
}
}
impl Drop for Res {
fn drop(&mut self) {
println!("close {}", self.0);
}
}
fn work(fail: bool) -> Result<(), String> {
let _a = Res::open("a");
let _b = Res::open("b");
if fail {
return Err("failed".into());
}
println!("body done");
Ok(())
}
fn main() {
println!("-- normal");
work(false).unwrap();
println!("-- early return");
let _ = work(true);
println!("-- moved value is closed by its new owner");
let r = Res::open("c");
let keeper = vec![r];
println!("moved into a Vec");
drop(keeper);
println!("end");
}-- normal
open a
open b
body done
close b
close a
-- early return
open a
open b
close b
close a
-- moved value is closed by its new owner
open c
moved into a Vec
close c
endThe Java run and the C# run printed the same sequence for the normal and failing cases (open a, open b, body done or the failure, close b, close a); Java and C# then printed the caught exception message failed. In Rust a failure is a Result, so the early return is a normal return, and the close lines come out in the same order. The last case has no equivalent in using: a value that is moved into a Vec is closed when the Vec is dropped, because that is its new owner.
How to do it#
- For each class that implements
IDisposableorAutoCloseable, make a struct that owns the resource and implementDrop. If the resource is already a Rust type (aFile), you need no wrapper. - Delete the
usingandtryblocks. Make sure each resource variable lives as long as it needs to, and no longer: control the lifetime with blocks ({ let f = File::open(..)?; ... }) ordrop(x). - Keep
dropsimple and infallible. If closing can fail and you must know, add an explicit method (close(self) -> Result<..>) and call it where you can report the error;dropcannot return one. - For resources owned by C code, wrap the handle in a struct and call the C
freeorcloseinDrop(see the thread on calling a C library).
Common mistakes#
- Using
let _ = Res::open("a");and expecting the resource to live on. A binding named_drops the value at once; name it_ato keep it until the end of the scope. - Relying on
dropfor something that must happen even if the process aborts or is killed. Destructors do not run in that case. - Putting slow or blocking work in
dropof something that is dropped inside a lock or a hot loop.
Related questions#
Is Drop the same as a C# finalizer?#
No. A finalizer runs at a time the garbage collector chooses, perhaps never. Drop runs at a fixed point in the program, every time.
What happens if the code panics?#
By default the stack unwinds and values still in scope are dropped on the way, so resources are released. A program built with panic = "abort" does not unwind.
Sources#
- The Rust Book, "Running Code on Cleanup with the Drop Trait": https://doc.rust-lang.org/book/ch15-03-drop.html
std::ops::Drop: https://doc.rust-lang.org/std/ops/trait.Drop.html