Resource Types & fn drop(self)
Some values represent things in the outside world — open files, sockets, GPU buffers, lock guards — and need explicit cleanup. Miri's answer is the fn drop(self) method. Defining one on a class or struct turns it into a resource type:
use system.io
// A type with `fn drop(self)` is a *resource type*.
// Miri runs `drop` exactly once when the value's lifetime ends.
class FileHandle
private path String
fn init(p String)
self.path = p
println(f"opened {self.path}")
fn drop(self)
println(f"closed {self.path}")
fn main()
let f = FileHandle(p: "config.toml")
println("doing work...")
// f goes out of scope here — `drop` fires automatically.
// No manual .close() needed.
- Miri guarantees
dropruns exactly once when the value's lifetime ends. - Resource types are single-owner — they cannot be shared via reference counting and they do not participate in Copy-on-Write.
- Resource types are intentionally not
Cloneable— most external resources cannot be meaningfully duplicated. - Aliasing a resource (
var alias = original) consumes the original, just like passing it to a function.
This is how Miri delivers RAII without manual .close() calls and without exception-handling ceremony.