Module 11 · Lifetimes & smart pointers
11.2Drop & smart pointers
How Rust cleans up every value at a point you can see, how to run your own cleanup with Drop, and the smart pointers Box, Cow and Deref that build on it.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Freeing memory | The garbage collector, at some later point | The garbage collector, at some later point | The owner, at the end of its scope: drop runs right there |
| Closing a file, lock or connection | Opt-in: try/finally, or using with [Symbol.dispose]() | Opt-in: IDisposable with using | Automatic for every value; impl Drop adds your own cleanup |
| Cleanup you forgot to ask for | Never runs; a FinalizationRegistry callback may run later, or never | Never runs, unless a finalizer runs later on the finalizer thread | Can't be forgotten; there's no keyword to leave out |
| Cleaning up early | Call the close method; later calls fail at run time, if the class checks | Call Dispose(); later calls throw ObjectDisposedException | drop(value); later uses are compile errors (E0382) |
| Return the input or a new string | Return a string either way | Return a string either way | Cow<'a, str>: borrowed when unchanged, owned when changed |
A garbage collector frees memory, but it doesn’t close files, release locks or return connections to a pool, at least not on any schedule you can rely on. So TypeScript gives you try/finally and, more recently, using declarations with [Symbol.dispose](). Both are opt-in: forget them and the cleanup never runs.So C# gives you IDisposable and using, which are opt-in: forget using and Dispose never runs, unless a finalizer catches it much later. Rust has no collector, so it already has to clean up every value at a fixed point: the end of its owner’s scope. Drop lets you hook your own code into that point. This lesson covers how that works, then the smart pointers built on it: Box<T>, Cow, and the Deref trait that makes them feel like plain references.
Every value is dropped
Here are two temporary files that must be deleted when the code is done with them. Each language deletes them in reverse order of creation; what differs is what you have to write.
class TempFile {
readonly name: string;
constructor(name: string) {
this.name = name;
}
delete(): void {
console.log(`delete ${this.name}`);
}
}
const report = new TempFile("report.tmp");
try {
const cache = new TempFile("cache.tmp");
try {
console.log(`using ${report.name} and ${cache.name}`);
} finally {
cache.delete();
}
} finally {
report.delete();
}using var report = new TempFile("report.tmp");
using var cache = new TempFile("cache.tmp");
Console.WriteLine($"using {report.Name} and {cache.Name}");
sealed class TempFile(string name) : IDisposable
{
public string Name { get; } = name;
public void Dispose() => Console.WriteLine($"delete {Name}");
}struct TempFile {
name: String,
}
impl TempFile {
fn new(name: &str) -> Self {
Self {
name: name.to_string(),
}
}
}
impl Drop for TempFile {
fn drop(&mut self) {
println!("delete {}", self.name);
}
}
fn main() {
let report = TempFile::new("report.tmp");
let cache = TempFile::new("cache.tmp");
println!("using {} and {}", report.name, cache.name);
} // `cache` is dropped, then `report`Output
using report.tmp and cache.tmp delete cache.tmp delete report.tmp
The try/finally version runs everywhere. TypeScript also has using declarations, which do the same with less nesting: put the cleanup in a [Symbol.dispose]() method and write using instead of const. Node 22, which this site checks snippets with, can’t run using yet, so this block is only type-checked:
class TempFile {
readonly name: string;
constructor(name: string) {
this.name = name;
}
[Symbol.dispose](): void {
console.log(`delete ${this.name}`);
}
}
using report = new TempFile("report.tmp");
using cache = new TempFile("cache.tmp");
console.log(`using ${report.name} and ${cache.name}`);impl Drop for TempFile is the Rust version of [Symbol.dispose]()IDisposable: one method, drop(&mut self), that runs just before the value’s memory is freed. The difference is in main. There’s no using and no finally. Rust drops every value when its owner goes out of scope, whether or not its type implements Drop, so there’s nothing to forget.
Drop order is fixed and you can rely on it:
- Local variables are dropped in reverse order of declaration. A later value may borrow from an earlier one, so it has to go first.
usingdeclarationsusing vardeclarations use the same order. - A struct runs its own
dropfirst, then drops its fields in declaration order. - An array or a
Vecdrops its elements from first to last. AVecthen frees its buffer.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
struct Pair {
first: Noisy,
second: Noisy,
}
impl Drop for Pair {
fn drop(&mut self) {
println!("drop pair");
}
}
fn main() {
let _pair = Pair {
first: Noisy("first"),
second: Noisy("second"),
};
let _list = [Noisy("item 0"), Noisy("item 1")];
println!("end of main");
}Output
end of main drop item 0 drop item 1 drop pair drop first drop second
_list was declared last, so it’s dropped first, and its items go in order. Then _pair: its own drop runs, then its fields. Types without a Drop impl are dropped the same way: a String frees its buffer, a Vec drops each element and frees its buffer. The compiler generates that code for every type; impl Drop only adds a step in front.
Drop also runs when a function leaves early, through return, ? or a panic (panics unwind the stack by default; a program built with panic = "abort" stops without dropping anything). That’s why Rust code rarely needs anything like finally: a lock guard, a file handle or a transaction rolls back or releases itself on every path out.
Mental model shiftDrop is not a finalizer
A C# finalizer (~TempFile()) runs on the finalizer thread, at some point after the collector notices the object is unreachable, and .NET doesn’t run finalizers when the process exits. Rust’s drop runs on the same thread, at the owner’s closing brace, unless you deliberately leak the value (see Under the hood). It’s Dispose with using applied automatically to every value, so you don’t need the Dispose(bool disposing) pattern or GC.SuppressFinalize.
Dropping early with drop
Sometimes you want cleanup before the end of the scope: release a lock before a slow operation, or close a file before deleting it. TypeScriptC# calls the cleanup method directly, and afterwards the object is still there, half-dead. Using it again is a bug you find at run time. Rust’s drop function takes the value, so using it again is a compile error.
class TempFile {
readonly name: string;
#deleted = false;
constructor(name: string) {
this.name = name;
}
write(text: string): void {
if (this.#deleted) {
throw new Error(`${this.name} is already deleted`);
}
console.log(`write ${text} to ${this.name}`);
}
delete(): void {
this.#deleted = true;
console.log(`delete ${this.name}`);
}
}
const report = new TempFile("report.tmp");
report.write("totals");
report.delete();
try {
report.write("more"); // compiles; fails when it runs
} catch (error) {
console.log(`error: ${(error as Error).message}`);
}var report = new TempFile("report.tmp");
report.Write("totals");
report.Dispose();
try
{
report.Write("more"); // compiles; throws when it runs
}
catch (ObjectDisposedException)
{
Console.WriteLine($"error: {report.Name} is already deleted");
}
sealed class TempFile(string name) : IDisposable
{
private bool deleted;
public string Name { get; } = name;
public void Write(string text)
{
ObjectDisposedException.ThrowIf(deleted, this);
Console.WriteLine($"write {text} to {Name}");
}
public void Dispose()
{
deleted = true;
Console.WriteLine($"delete {Name}");
}
}struct TempFile {
name: String,
}
impl TempFile {
fn new(name: &str) -> Self {
Self {
name: name.to_string(),
}
}
fn write(&self, text: &str) {
println!("write {text} to {}", self.name);
}
}
impl Drop for TempFile {
fn drop(&mut self) {
println!("delete {}", self.name);
}
}
fn main() {
let report = TempFile::new("report.tmp");
report.write("totals");
drop(report); // deleted here
report.write("more");
}Output of the TypeScriptC# version
write totals to report.tmp delete report.tmp error: report.tmp is already deleted
Rust doesn't compile this: error E0382
error[E0382]: borrow of moved value: `report`
--> early.rs:27:5
|
24 | let report = TempFile::new("report.tmp");
| ------ move occurs because `report` has type `TempFile`, which does not implement the `Copy` trait
25 | report.write("totals");
26 | drop(report); // deleted here
| ------ value moved here
27 | report.write("more");
| ^^^^^^ value borrowed here after move
|
note: if `TempFile` implemented `Clone`, you could clone the value
--> early.rs:1:1
|
1 | struct TempFile {
| ^^^^^^^^^^^^^^^ consider implementing `Clone` for this type
...
26 | drop(report); // deleted here
| ------ you could clone this valuedrop isn’t special. It’s an ordinary function in the standard library, and its whole body is empty: pub fn drop<T>(_x: T) {}. Passing report moves it into drop, and drop’s parameter goes out of scope at its closing brace, which runs TempFile::drop. After the move, report can’t be used, so the bug TypeScriptC# finds at run time is E0382, “borrow of moved value”, here. The ownership lesson covers moves.
An inner block does the same without a function call: { let report = TempFile::new("report.tmp"); ... } deletes the file at the block’s closing brace.
Box<T>: one value on the heap
A smart pointer is a type that owns some data, acts like a reference to it, and cleans it up when dropped. You’ve already used several: String owns a text buffer, Vec<T> owns an array, and Box<T> owns one value on the heap. Stack vs. heap introduced Box<T> for recursive types. Dropping a Box drops the value inside, then frees the heap allocation.
The other everyday use is a trait object: a value whose concrete type is only known at run time, like a variable typed with an interface in TypeScriptC#. A list of different shapes can’t be a Vec<Circle> or a Vec<Square>; it’s a Vec<Box<dyn Shape>>. Each element is a box holding some type that implements Shape.
interface Shape {
area(): number;
}
class Circle implements Shape {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
class Square implements Shape {
readonly side: number;
constructor(side: number) {
this.side = side;
}
area(): number {
return this.side * this.side;
}
}
const shapes: Shape[] = [new Circle(1), new Square(2)];
for (const shape of shapes) {
console.log(shape.area().toFixed(2));
}List<IShape> shapes = [new Circle(1), new Square(2)];
foreach (var shape in shapes)
{
Console.WriteLine(shape.Area().ToString("F2"));
}
interface IShape
{
double Area();
}
record Circle(double Radius) : IShape
{
public double Area() => Math.PI * Radius * Radius;
}
record Square(double Side) : IShape
{
public double Area() => Side * Side;
}use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
PI * self.radius * self.radius
}
}
struct Square {
side: f64,
}
impl Shape for Square {
fn area(&self) -> f64 {
self.side * self.side
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { radius: 1.0 }),
Box::new(Square { side: 2.0 }),
];
for shape in &shapes {
println!("{:.2}", shape.area());
}
}Output
3.14 4.00
In TypeScriptC#, every object is already behind a reference, so a list of interface values needs nothing special. In Rust, Circle and Square are different types, which in general have different sizes, and a Vec stores elements of one type inline. So each shape goes in its own heap allocation, and the vector holds the boxes, which all have the same type and size. When shapes is dropped, it drops each box, which drops each shape and frees its allocation. impl Trait vs. dyn Trait covers when you need dyn and when a generic does the job without any box.
Deref: acting like a reference
Why can you call shape.area() on a Box<dyn Shape>, or name.len() on a String that’s inside a Box? Because Box<T> implements the Deref trait. Deref says “this type can be used as a &Target”, and Rust uses it in two places:
*valueon a smart pointer means*value.deref(): the value inside.- Method calls and
&arguments followDerefautomatically, as many steps as needed. This is deref coercion: it’s why a&Stringcan be passed where a&stris expected (Stringderefs tostr), and a&Vec<T>where a&[T]is expected.
Here’s a small smart pointer of your own: a wrapper that logs when it’s dropped, and otherwise behaves like the value it holds.
use std::ops::Deref;
struct Tracked<T> {
label: &'static str,
value: T,
}
impl<T> Deref for Tracked<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T> Drop for Tracked<T> {
fn drop(&mut self) {
println!("drop {}", self.label);
}
}
fn shout(text: &str) -> String {
text.to_uppercase()
}
fn main() {
let name = Tracked {
label: "name",
value: String::from("Ada"),
};
println!("{} letters", name.len()); // Tracked<String> -> String: `len` is found on String
println!("{}", shout(&name)); // &Tracked<String> -> &String -> &str
}Output
3 letters ADA drop name
name.len() isn’t a method of Tracked, so Rust looks through Deref and finds it on String. shout(&name) needs a &str; Rust follows Deref twice, from &Tracked<String> to &String to &str. All of this is decided at compile time, and each step is an ordinary deref call that the optimizer usually reduces to a pointer into the value. TypeScript has nothing like it; a Proxy can intercept property access at run time, but that’s a different, much heavier tool. The nearest C# feature is a user-defined implicit conversion operator, but Rust applies Deref only to references and method calls, so it never creates a new value behind your back.
Cow: borrow when you can, own when you must
Here’s a function that spells out & as “and” in a title. Most titles don’t contain &, so it should return the input unchanged without copying it, and only build a new string when it has to. In TypeScriptC#, returning either the input or a new string needs nothing special: both are references to stringsstring objects the garbage collector looks after, so one return type covers both. In Rust, returning String would copy every title, and returning &str can’t hold new text. Cow holds either.
function spellOut(title: string): string {
return title.includes("&") ? title.replaceAll("&", "and") : title;
}
for (const title of ["Pride and Prejudice", "Tom & Jerry"]) {
const result = spellOut(title);
console.log(`${result}: ${result === title ? "no copy" : "new string"}`);
}foreach (var title in new[] { "Pride and Prejudice", "Tom & Jerry" })
{
var result = SpellOut(title);
Console.WriteLine($"{result}: {(ReferenceEquals(result, title) ? "no copy" : "new string")}");
}
static string SpellOut(string title) => title.Contains('&') ? title.Replace("&", "and") : title;use std::borrow::Cow;
fn spell_out(title: &str) -> Cow<'_, str> {
if title.contains('&') {
Cow::Owned(title.replace('&', "and"))
} else {
Cow::Borrowed(title)
}
}
fn main() {
for title in ["Pride and Prejudice", "Tom & Jerry"] {
let result = spell_out(title);
let kind = if matches!(result, Cow::Borrowed(_)) {
"no copy"
} else {
"new string"
};
println!("{result}: {kind}");
}
}Output
Pride and Prejudice: no copy Tom and Jerry: new string
One honest caveat about the TypeScript version: JavaScript can’t tell you whether two strings are the same object. === compares the text, so "no copy" here only means the text came back unchanged. Rust’s Cow makes the difference visible in the type: Cow::Borrowed is the original, untouched, and only Cow::Owned allocated.
Cow stands for “clone on write”. Cow<'a, str> is an enum with two variants:
Cow::Borrowed(&'a str): a borrow, tied to the input by the lifetime'a(Lifetimes explains the'_).Cow::Owned(String): a new string theCowowns.
Callers rarely care which one they got. Cow<str> implements Deref<Target = str>, so result.len(), println!("{result}") and passing &result where a &str is expected all work. When you need a String, result.into_owned() gives you one, copying only if it was borrowed. result.to_mut() gives you a &mut String to change, copying first only if it was borrowed. That’s the “clone on write” in the name.
Cow works for any borrowed/owned pair: Cow<'a, [T]> for &[T] and Vec<T>, Cow<'a, Path> for paths. You’ll mostly meet it in APIs that usually borrow, such as String::from_utf8_lossy, which returns Cow<str> and only allocates when it has to replace invalid bytes.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| Nothing (automatic drop) | Almost always. The default. | Every value is dropped at the end of its owner’s scope, including String, Vec, files and locks from the standard library. | Let the variable go out of scope. |
impl Drop | Your type holds something that needs releasing that the compiler can’t see: an OS handle, a lock, a log entry to write when a task ends. | Runs on every exit path, including ? and panics, with nothing for callers to remember. | impl Drop for TempFile { fn drop(&mut self) { ... } } |
drop(value) or an inner block | Cleanup must happen before the end of the scope: releasing a lock before slow work, closing a file before deleting it. | Later uses become compile errors instead of run-time bugs. | drop(report);, or { let report = ...; } |
Box<T> | A recursive type, or a very large value you move often. | One value on the heap with one owner, freed when the box is dropped. | Box::new(value) |
Box<dyn Trait> | A value whose concrete type is only known at run time, such as a list of mixed shapes. | Different types, one element type. | Vec<Box<dyn Shape>>, Box::new(Circle { radius: 1.0 }) |
Cow<'a, str> | A function usually returns its input unchanged, but sometimes has to build a new value. | No copy in the common case, without making the caller deal with two return types. | Cow::Borrowed(title) or Cow::Owned(new_title) |
impl Deref | Your type is a smart pointer or a transparent wrapper around one value. | Callers use it like a reference to the inner value. | impl<T> Deref for Tracked<T> { type Target = T; ... } |
Rule of thumb: let scopes do the cleanup, and write impl Drop only for types that hold a resource. Reach for drop(value) when the cleanup must happen sooner. Use Box for recursive types and trait objects, Cow when a function usually doesn’t need to copy, and implement Deref only for pointer-like types.
Under the hood
The compiler inserts the drop calls itself. At each closing brace, it adds a call that drops each variable still owned in that scope, in reverse order of declaration. Types without Drop impls get generated code (often called drop glue) that drops their fields; for a plain i32 or a struct of numbers there’s nothing to do, so nothing is generated. Moved-from variables are skipped. When a value is moved on only some paths, the compiler keeps a hidden boolean, a drop flag, and checks it at the end of the scope:
struct TempFile(&'static str);
impl Drop for TempFile {
fn drop(&mut self) {
println!("delete {}", self.0);
}
}
fn archive(file: TempFile) {
println!("archive {}", file.0);
} // `file` is dropped here
fn finish(keep: bool) {
let file = TempFile("report.tmp");
if keep {
archive(file); // moved on this path only
}
println!("finish");
} // dropped here only if it wasn't moved
fn main() {
finish(true);
finish(false);
}Output
archive report.tmp delete report.tmp finish finish delete report.tmp
A Box<dyn Shape> is one pointer wider than a Box<Circle>. The extra pointer leads to a vtable: a table the compiler builds for each type and trait pair. Its exact layout isn’t guaranteed; today it holds how to drop the type, its size and alignment, and its trait methods. That’s how dropping a box drops a Circle correctly without the Vec knowing which type is inside:
let shape: Box<dyn Shape> = Box::new(Circle { radius: 1.0 });
println!("Box<Circle>: {} bytes", size_of::<Box<Circle>>());
println!("Box<dyn Shape>: {} bytes", size_of::<Box<dyn Shape>>());
println!("{:.2}", shape.area());Output
Box<Circle>: 8 bytes Box<dyn Shape>: 16 bytes 3.14
Rust doesn’t promise that every value is dropped. A value that’s never freed is a leak, not a safety problem, so safe code can cause one: std::mem::forget(value) skips the drop on purpose, std::process::exit ends the program without unwinding, and two reference-counted values that point at each other keep each other alive. The next lesson shows that last case and how Weak<T> avoids it. Within normal control flow, though, drops happen exactly where the code says.
Common pitfalls
Common pitfalllet _ = value drops it at once
let _guard = TempFile::new("report.tmp"); keeps the file until the end of the scope. let _ = TempFile::new("report.tmp"); drops it on the same line, because _ isn’t a variable: nothing owns the value. With a lock guard, that means you never held the lock at all.
let _ = TempFile("first.tmp");
let _guard = TempFile("second.tmp");
println!("end of scope");Output
delete first.tmp end of scope delete second.tmp
Name anything you keep for its cleanup, starting with an underscore if you don’t otherwise use it.
Common pitfallYou can't call .drop() yourself
Drop::drop runs automatically, and calling it directly would run the cleanup twice: once now and once at the end of the scope. The compiler forbids it:
struct TempFile(&'static str);
impl Drop for TempFile {
fn drop(&mut self) {
println!("delete {}", self.0);
}
}
fn main() {
let file = TempFile("report.tmp");
file.drop();
}Rust doesn't compile this: error E0040
error[E0040]: explicit use of destructor method --> main.rs:11:10 | 11 | file.drop(); | ^^^^ explicit destructor calls not allowed | help: consider using `drop` function | 11 - file.drop(); 11 + drop(file); |
Call the free function drop(file) instead. It takes ownership, so the cleanup runs once.
Common pitfallCopy types can't have Drop
A type that’s Copy is duplicated by plain assignment, so a Drop impl would run once per copy. Rust doesn’t allow the two together:
#[derive(Clone, Copy)]
struct Handle(u32);
impl Drop for Handle {
fn drop(&mut self) {}
}Rust doesn't compile this: error E0184
error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor --> main.rs:1:17 | 1 | #[derive(Clone, Copy)] | ^^^^ `Copy` not allowed on types with destructors
A type that owns a resource shouldn’t be Copy anyway: two copies would both think they own it. Derive Clone only if a copy really should get its own resource.
Common pitfallDeref isn't inheritance
Implementing Deref<Target = Base> on a Derived struct makes derived.base_method() compile, and it can look like a way to port a class hierarchy. Don’t: generic code that asks for a trait won’t accept Derived, and readers won’t expect a plain struct to act like a pointer. Share behavior with traits, and implement Deref only for smart pointers and thin wrappers.
Try it yourself
Exercise: port this to Rust
Port this build log to Rust. Each Section prints enter when it’s created and leave when it’s done. Use Drop, so that leaving happens automatically at the end of each scope.
class Section {
readonly name: string;
constructor(name: string) {
this.name = name;
console.log(`enter ${name}`);
}
close(): void {
console.log(`leave ${this.name}`);
}
}
function build(): void {
const all = new Section("build");
try {
for (const step of ["compile", "link"]) {
const section = new Section(step);
try {
console.log(`work on ${step}`);
} finally {
section.close();
}
}
} finally {
all.close();
}
}
build();Build();
static void Build()
{
using var all = new Section("build");
foreach (var step in new[] { "compile", "link" })
{
using var section = new Section(step);
Console.WriteLine($"work on {step}");
}
}
sealed class Section : IDisposable
{
private readonly string name;
public Section(string name)
{
this.name = name;
Console.WriteLine($"enter {name}");
}
public void Dispose() => Console.WriteLine($"leave {name}");
}Expected output
enter build enter compile work on compile leave compile enter link work on link leave link leave build
Show a hint
Give Section a Drop impl that prints the leave line, and print the enter line in a new function. In the loop, keep the guard in a named variable such as _section; let _ = would drop it straight away.
Show a solution
struct Section {
name: String,
}
impl Section {
fn new(name: &str) -> Self {
println!("enter {name}");
Self {
name: name.to_string(),
}
}
}
impl Drop for Section {
fn drop(&mut self) {
println!("leave {}", self.name);
}
}
fn build() {
let _all = Section::new("build");
for step in ["compile", "link"] {
let _section = Section::new(step);
println!("work on {step}");
}
}
fn main() {
build();
}Each Section is dropped at the end of the scope that owns it: _section at the end of each loop iteration, _all at the end of build. The compiler inserts the drops, so there's no finally and no using to forget, and the nesting in the output comes from the nesting of the scopes.
Saved in this browser only.