Skip to content
ImagineWorld

Rust Fundamentals for OOP Developers

node_idnode-book_oop-to-rust_chapter-02-rust-fundamentals-for-oop-developers
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleRust Fundamentals for OOP Developers
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Rust Fundamentals for OOP Developers

Section titled “Chapter 2 — Rust Fundamentals for OOP Developers”

Sapere aude. (Dare to know.)

Memory safety without garbage collection. Data race prevention at compile time. Explicit handling of absence and failure. These are not language features in the conventional sense. They are properties that emerge from a handful of foundational concepts that permeate all Rust programming. Understanding these concepts is the intellectual core of the transition from object-oriented thinking.

Ownership, borrowing, and lifetimes form the foundation, along with the type system mechanisms that make Rust’s safety guarantees enforceable. These ideas will feel unfamiliar at first. The borrow checker will reject code that your intuition says should work. The frustration is normal and temporary. Once these concepts become natural, they transform from obstacles into powerful tools for expressing intent.

Expression-oriented programming

Chapter 1 introduced the distinction between statements and expressions, noting that Rust collapses this distinction: nearly everything in Rust is an expression that produces a value. This section explores the mechanics and implications of that design in detail. Understanding expression-oriented programming is foundational because it shapes how values flow through code and how you structure logic.

Blocks as expressions

In languages like Java or C#, a block delimited by braces is simply a grouping mechanism for statements. It controls scope but produces no value. In Rust, a block is an expression that evaluates to the value of its final expression (the one without a trailing semicolon).

let area = {
let width = 10;
let height = 5;
width * height // No semicolon: this is the block's value
};

The variables width and height exist only within the block. They are computed, used to calculate the area, and then discarded when the block ends. Only the final result escapes. This pattern keeps intermediate computations local without requiring a separate function for simple sequences.

The distinction between expressions and statements comes down to the semicolon. An expression produces a value; adding a semicolon turns it into a statement that produces the unit type (). This is why the final expression in a block lacks a semicolon: the semicolon would discard the value.

let result = {
let x = 5;
x + 1; // Semicolon makes this a statement returning ()
};
// result is now () rather than 6

This rule catches some developers by surprise when they habitually add semicolons everywhere. The compiler will warn when it detects that a block evaluates to () (known as the unit type and equivalent to void in other languages) when a different type was expected. Learning to read these warnings is part of developing Rust fluency.

If and match return values

Conditional expressions in Rust are expressions, not statements. An if-else produces the value of whichever branch executes:

let category = if score >= 90 {
"excellent"
} else if score >= 70 {
"good"
} else {
"needs improvement"
};

Both branches must produce values of the same type. The compiler enforces this, rejecting code where branches return incompatible types. This requirement eliminates an entire class of bugs where one branch was forgotten or returns the wrong type.

The absence of an else branch is permitted only when the if expression is used as a statement (for its side effects) rather than for its value. When used as an expression, the else branch is mandatory because the expression must produce a value regardless of which path is taken.

Match expressions provide similar value-producing behavior with exhaustiveness checking:

let description = match http_status {
200 => "OK",
201 => "Created",
400 => "Bad Request",
404 => "Not Found",
500..=599 => "Server Error",
_ => "Unknown",
};

The compiler verifies that every possible value is handled. For enums, this means every variant must have a matching arm. For integers, either every value must be covered or a wildcard pattern must catch the remainder. This exhaustiveness checking transforms match from a convenience into a safety mechanism. When you add a variant to an enum, the compiler points to every match that needs updating.

The value-producing nature of match encourages a different style than switch statements in other languages. Rather than setting a variable inside each case, the match expression directly produces the result. Each arm is an expression, and all arms must produce compatible types.

Match expressions support guards, additional conditions that refine when a pattern matches. A guard appears after the pattern, introduced by the if keyword:

enum Command {
Move { x: i32, y: i32 },
Write(String),
Quit,
}
fn execute(cmd: Command) {
match cmd {
Command::Move { x, y } if x > 0 && y > 0 => {
println!("Moving to positive quadrant: ({}, {})", x, y);
}
Command::Move { x, y } if x == 0 || y == 0 => {
println!("Moving along axis: ({}, {})", x, y);
}
Command::Move { x, y } => {
println!("Moving to: ({}, {})", x, y);
}
Command::Write(msg) if msg.is_empty() => {
println!("Empty message, skipping");
}
Command::Write(msg) => {
println!("Writing: {}", msg);
}
Command::Quit => println!("Quitting"),
}
}

The guards allow finer-grained control over which arm executes. When a pattern matches but its guard evaluates to false, the match continues to the next arm. This enables expressing complex conditional logic while maintaining the exhaustiveness guarantees that make match safe. The final Command::Move arm catches all moves not handled by the guarded arms above it.

Implications for control flow

The expression-oriented design affects how you structure entire functions. A function’s return value is the value of its body expression:

fn classify_temperature(celsius: f64) -> &'static str {
if celsius < 0.0 {
"freezing"
} else if celsius < 20.0 {
"cold"
} else if celsius < 30.0 {
"comfortable"
} else {
"hot"
}
}

No explicit return keyword is needed when the function body is a single expression. The return keyword remains available for early exits:

fn find_first_positive(numbers: &[i32]) -> Option<i32> {
for &n in numbers {
if n > 0 {
return Some(n);
}
}
None
}

The early return handles the found case, while the final None handles the exhausted-without-finding case. Both paths produce the same type, Option<i32>.

This expression orientation interacts elegantly with Rust’s error handling. The ? operator, covered later in this book, leverages expressions to propagate errors concisely. Functions can be structured as a series of fallible operations, with each step either producing a value to continue with or short-circuiting to return an error.

The mental shift from statements to expressions takes practice. Developers accustomed to imperative styles often write Rust code that declares mutable variables and assigns to them in branches. This works but misses the expressiveness Rust offers. As fluency develops, you find yourself writing code where values flow through expressions rather than accumulating through mutation. The result is code that is often shorter, always clearer about data flow, and less prone to bugs involving uninitialized or incorrectly assigned variables.

How expressions enable immutability

The connection between expression-oriented syntax and immutability is one of the most practical benefits Rust offers to developers transitioning from object-oriented languages. In Java, C#, or C++, conditional initialization creates an unavoidable tension: the language requires declaring a variable before assigning to it conditionally, which means the variable must be mutable even when reassignment is never intended.

Consider a common scenario: determining a user’s permission level based on their role. In Java, the code requires declaring the variable first, then assigning within each branch:

String permissionLevel;
if (role.equals("admin")) {
permissionLevel = "full";
} else if (role.equals("editor")) {
permissionLevel = "write";
} else {
permissionLevel = "read";
}

The permissionLevel variable must accept assignment, which means it remains mutable for the rest of its scope. Nothing in the language prevents accidental reassignment later in the function. Developers might add a comment noting that the variable should not change, or adopt naming conventions to signal intent, but these are social contracts rather than compiler-enforced guarantees. The IDE will not warn if someone modifies permissionLevel fifty lines later during a late-night debugging session.

In Rust, because if is an expression that produces a value, the same logic results in an immutable binding:

let permission_level = if role == "admin" {
"full"
} else if role == "editor" {
"write"
} else {
"read"
};

The binding is initialized in a single statement. There is no moment when permission_level exists without a value, and there is no syntactic opportunity to accidentally reassign it afterward. Attempting to write permission_level = “other”; later in the function produces a compile error. The compiler enforces what in other languages would be a comment, a naming convention, or wishful thinking.

This distinction might seem minor in isolation, but it compounds across a codebase. Every conditional initialization in object-oriented code creates a mutable variable that could theoretically change. Every conditional initialization in Rust creates an immutable binding by default. Over thousands of lines, this shifts the baseline assumption. When reading Rust code, encountering a binding without mut means that binding will not change. When reading Java code, encountering a variable without final means nothing about the programmer’s intent.

The pattern extends beyond simple conditionals to any computation that builds a result through multiple steps. Statement-oriented languages typically require declaring a mutable accumulator, performing operations on it, and then using the final state. The accumulator remains mutable throughout its scope, even after the computation is complete.

Rust’s block expressions offer an alternative. A block can contain multiple statements, with the final expression becoming the block’s value. Any mutable state needed for the computation exists only within the block:

let processed = {
let mut temp = Vec::new();
for item in &items {
if predicate(item) {
temp.push(transform(item));
}
}
temp
};

The mutable temp vector exists only within the braces. Once the block completes, only the final value escapes, bound to the immutable processed variable. The mutation is confined to the smallest possible scope, invisible to surrounding code. This pattern appears throughout idiomatic Rust: complex initialization logic wrapped in a block, with only the result visible outside.

Iterator methods push this even further by eliminating explicit mutation entirely. A chain of filter, map, and collect calls expresses the same logic without any mutable binding appearing in the source code. The mutation happens internally within the iterator machinery, invisible to the code that uses it.

The expression-oriented design does not eliminate mutation from Rust programs. Mutation remains available and sometimes necessary. What changes is the relationship between the default and the exception. In object-oriented languages, mutability is the default and immutability requires annotation. In Rust, immutability is the default and mutability requires annotation. This inversion, combined with expressions that enable initializing immutable bindings from complex logic, means that typical Rust code contains far fewer mutable variables than equivalent code in other languages. The mutation that does exist stands out, marked explicitly with mut, making code review and reasoning substantially easier.

Default immutability and its consequences

Rust variables are immutable by default. This seems like a minor syntactic detail until you consider how profoundly it changes the way code is written and reasoned about. When you write let x = 5; in Rust, that binding cannot be reassigned. Attempting to write x = 6; afterward produces a compile error. To create a mutable variable, you must explicitly request mutability by writing let mut x = 5; instead.

In Java, C#, and C++, mutability is the default. Final, const, or readonly annotations opt into immutability. This seems like equivalent flexibility, but the default matters enormously. Defaults shape habits. When immutability requires extra syntax, developers use it sparingly, often only when they remember to add the annotation. When mutability requires extra syntax, developers reach for it only when genuinely needed. The cognitive burden shifts from “remember to mark things immutable” to “justify why this needs to change.”

The consequences of this design choice ripple through entire codebases in ways that become apparent only after working with Rust for a sustained period. When you see a variable binding without mut, you know with absolute certainty that it will not change for the remainder of its scope. When you read a function signature that takes &T rather than &mut T, you know the function cannot modify the borrowed data. These guarantees are not comments or conventions that might become stale as code evolves; they are enforced by the compiler on every build.

Consider how this affects reasoning about code in a large system. In an object-oriented codebase, any method call might mutate its receiver or its arguments. A method named getUser() might cache results internally, modifying the object’s state. A method named validate() might normalize data as a side effect. Understanding what a piece of code does requires examining not only that code but every method it calls, transitively through the entire call graph. In Rust, immutability is visible in the types. A function that takes &self cannot modify the struct (barring interior mutability, discussed later). A function that takes &T cannot modify T. The type signature constrains what the implementation can do, and readers can trust those constraints without examining the implementation.

This extends naturally to concurrent programming, where immutability provides even greater benefits. Immutable data can be safely shared across threads without synchronization because no thread can modify it. When mutation is rare and explicit, identifying what needs synchronization becomes tractable. Rather than assuming everything might be shared and modified, developers can trace the mut annotations to find exactly where synchronization is required. The borrow checker enforces that mutable access is exclusive, preventing the data races that plague concurrent code in other languages.

Ownership and borrowing: the core insight

Chapter 1 explained that Rust achieves memory safety without garbage collection. Ownership is the mechanism that makes this possible. The concept is straightforward to state: every value in Rust has exactly one owner, and when that owner goes out of scope, the value is dropped (its memory is freed). A string allocated on the heap, for instance, is owned by the variable it is assigned to. When that variable’s scope ends, Rust automatically deallocates the string. There is no garbage collector running in the background, no reference counting overhead on every assignment, and no manual calls to free memory that might be forgotten or duplicated.

This single-owner rule creates ownership chains. When a struct contains another struct, the outer struct owns the inner one. When a vector contains strings, the vector owns those strings. Each owner in the chain bears sole responsibility for disposing what it owns. When an owner is dropped, everything it owns is dropped as well, recursively through the entire chain. This cascade of destruction is automatic and happens without any explicit cleanup code.

The following diagram illustrates an ownership chain in a typical data structure:

graph TD
    subgraph FS["Function Scope"]
        U["user: User"]
    end
    subgraph US["User struct"]
        N["name: String"]
        A["address: Address"]
    end
    subgraph AS["Address struct"]
        S["street: String"]
        C["city: String"]
    end
    U -- owns --> US
    A -- owns --> AS

[!visual-conversion] Ownership chain: the function scope owns the User, which owns its fields, which own their fields. Print diagram (PDF 057, printed p. 55) recreated in Mermaid; nested frames and “owns” edges as printed.

When the function returns and the user variable goes out of scope, Rust drops the entire chain. The User struct is dropped, which triggers dropping its name and address fields. Dropping the Address triggers dropping its street and city fields. Every String in the chain deallocates its heap buffer. All of this happens automatically because each owner is responsible for what it owns.

This resembles RAII (Resource Acquisition Is Initialization) in C++, but with a crucial difference: Rust enforces ownership at compile time rather than relying on programmer discipline. You cannot accidentally create a dangling pointer because the compiler tracks ownership through every assignment, function call, and scope boundary. It rejects programs that would access dropped values before they ever run.

The complexity arises when values need to be used in multiple places. In garbage-collected languages, this is trivial: copy the reference, and the garbage collector will clean up when all references disappear. In C++ it requires discipline and documentation: who is responsible for retention? Who can access the pointer after the owner deletes it? The burden falls on code review and programmer vigilance.

In Rust, there are two primary mechanisms for sharing access without shared ownership: moving ownership and borrowing. Understanding when to use each is fundamental to writing effective Rust code.

Moving ownership

When a value is assigned to a new variable or passed to a function, ownership transfers to the new owner. The original binding becomes invalid and cannot be used. This surprises developers from garbage-collected languages, where both the old and new variable would refer to the same heap data. It surprises C++ developers, who expect a copy. Rust’s move semantics mean that when ownership transfers, the original binding no longer exists from the compiler’s perspective.

The rationale for this design becomes clear when you consider memory safety. If both the original and new binding owned the same heap data, both would try to free it when going out of scope, causing a double free and memory corruption. If the original remained valid but did not own the data, it would become a dangling pointer when the new owner dropped the value. Move semantics avoid both problems by ensuring exactly one owner at all times.

Understanding exactly when moves occur is essential for working effectively with Rust. Moves happen in several specific situations, each of which transfers ownership from one binding to another.

Assignment to a new variable is the most straightforward case. Writing let b = a; moves the value from a to b. After this statement, a is no longer valid and cannot be used. The ownership chain that previously rooted at a now roots at b.

Passing a value to a function moves ownership into the function’s parameter. When calling process(data), the data binding transfers ownership to the function’s parameter. The caller can no longer use data after the call. The function becomes responsible for the value and, unless it returns the value back or stores it elsewhere, the value is dropped when the function ends.

Returning a value from a function moves ownership to the caller. When a function returns a String, for example, the caller receives ownership of that String. The function relinquishes its claim, and the caller becomes responsible for eventual disposal.

Constructing a struct or enum moves the field values into the new instance. When writing User { name: n, age: a }, the values bound to n and a move into the struct. The original bindings become invalid. The struct now owns these values.

Pattern matching with destructuring can move values out of a container. Matching against Some (x) moves the contained value into x, consuming the Option. The original Option can no longer be used because its contents have been taken.

The following diagram shows how a move operation transfers an entire ownership chain:

graph TD
    subgraph BEFORE["Before: let b = a"]
        A1["a: User"] --> N1["name: String"]
        A1 --> D1["address: Address"]
    end
    subgraph AFTER["After: let b = a"]
        B2["b: User"] --> N2["name: String"]
        B2 --> D2["address: Address"]
        X2["a: (invalid)"]
    end
    BEFORE -- move --> AFTER

[!visual-conversion] Moving a value transfers the entire ownership chain; the original binding becomes invalid. Print diagram (PDF 060, printed p. 58) recreated in Mermaid; all labels verbatim.

The key insight is that a move transfers the entire ownership chain rooted at the moved value. Moving a User that owns a String and an Address does not move just the User struct. The entire tree of owned data follows. The new owner assumes responsibility for all of it, and the original binding loses access to all of it.

Moves are not copies. When a String moves, no bytes are copied from one heap allocation to another. The stack data (the pointer, length, and capacity) may be copied to the new location, but the heap allocation itself remains in place. The move is a transfer of responsibility, not a duplication of data. This makes moves efficient regardless of how much data the value owns.

For simple types like integers and floating-point numbers, assignment creates a copy rather than a move. These types implement the Copy trait, indicating that a bitwise copy is sufficient to duplicate the value. The original remains valid because both the original and the copy are independent values with no shared heap allocation. The distinction between types that move and types that copy aligns with whether the type manages resources. Types that own heap memory, file handles, or network connections move; types that are entirely stack-based typically copy.

The following diagram contrasts move and copy behavior:

graph TD
    subgraph MOVE["Move (String,"]
        M1["a: String"] -- "let b = a" --> M2["b: String"] --> M3["a becomes invalid"]
    end
    subgraph COPY["Copy (i32, f64,"]
        C1["a: i32 = 5"] -- "let b = a" --> C2["b: i32 = 5"] --> C3["a: i32 = 5 (still valid)"]
    end

[!visual-conversion] Move types invalidate the source; Copy types duplicate the value and both remain valid. Print diagram (PDF 062, printed p. 60) recreated in Mermaid; two stacked panels. The panel titles are cut off in the print itself (“Move (String,”, “Copy (i32, f64,”) and are transcribed as printed.

Types that manage external resources cannot implement Copy because duplicating them would create multiple owners of the same resource. A File handle moved to a new binding ensures exactly one owner will close the file. Two copies of a File handle would both attempt to close the same file descriptor, causing errors or undefined behavior.

What actually happens during a move

The term “move” suggests something dramatic, as if data physically relocates from one place to another. The reality is more subtle. A move in Rust consists of two operations: a bitwise copy of the stack data, followed by the compile-time invalidation of the source variable. At the machine level, the CPU performs an ordinary memory copy. At the semantic level, the compiler tracks that the source no longer owns the value.

Consider a String in Rust. The variable itself lives on the stack and contains three pieces of information: a pointer to heap-allocated character data, the current length of the string, and the allocated capacity. On a 64-bit system, this metadata occupies 24 bytes. The actual characters live on the heap, potentially far from the stack frame.

let a = String::from("Hello");
let b = a;

The assignment copies those 24 bytes from a’s stack location to b’s stack location. The heap data remains untouched. Both a and b now contain identical metadata, including identical pointers to the same heap allocation. In C++, this would create two variables believing they own the same memory, each ready to free it when going out of scope. Rust prevents this catastrophe through compile-time tracking. After the assignment, the compiler marks a as invalid. Any subsequent attempt to use a produces a compile error, not a runtime crash.

The following diagram illustrates this transformation:

graph TD
    subgraph BEFORE["Before: let b = a"]
        A1["a (valid)"] --> H1["Heap: 'Hello'"]
    end
    subgraph AFTER["After: let b = a"]
        A2["a (invalid)"] -.-> H2["Heap: 'Hello'"]
        B2["b (valid)"] --> H2
    end
    BEFORE --> AFTER

[!visual-conversion] A move copies stack metadata while invalidating the source; heap data stays in place. Print diagram (PDF 064, printed p. 62) recreated in Mermaid; the dotted edge from a (invalid) is dotted in print.

The crucial insight is that move semantics are a compile-time abstraction layered over runtime operations that have existed since the dawn of computing. The machine performs a memcpy. The compiler performs ownership tracking. Neither knows about the other, and yet together they provide memory safety without garbage collection.

Closures and the move keyword

Closures capture variables from their environment, and by default they capture by the least restrictive method that satisfies their needs: by reference if they only read, by mutable reference if they modify. Sometimes a closure needs to take ownership of captured variables, particularly when the closure outlives the scope where it was created. The move keyword forces ownership transfer.

fn create_counter() -> impl FnMut() -> i32 {
let mut count = 0;
move || {
count += 1;
count
}
}

Without move, this code would not compile. The closure would try to capture count by mutable reference, but count lives on the stack frame of create_counter, which disappears when the function returns. With move, the closure takes ownership of count, and the value moves into the closure itself, living as long as the closure lives. Because the closure modifies its captured count, it implements FnMut rather than Fn, so the return type is impl FnMut() -> i32 and callers need a mutable binding (let mut counter = create_counter();).

Iteration and consumption

The iterator methods in Rust’s standard library provide a clear illustration of move semantics in practice. Three methods exist for iterating over collections, and their names signal their ownership behavior.

The method into_iter() consumes the collection, taking ownership of each element. After iteration completes, the collection no longer exists. The method iter() borrows the collection immutably, providing references to each element. The collection remains valid and unchanged after iteration. The method iter_mut() borrows the collection mutably, allowing modification of elements in place.

let names = vec![
String::from("Alice"),
String::from("Bob"),
String::from("Carol"),
];
// This consumes the vector
for name in names {
println!("Hello, {}", name);
}
// names is invalid here

The bare for name in names syntax desugars to for name in names.into_iter(). Each String moves out of the vector and into the loop variable name. When the loop body ends, name goes out of scope and the string is dropped. After all iterations complete, the vector’s heap allocation is also freed.

If the collection must survive iteration, borrow it:

let names = vec![
String::from("Alice"),
String::from("Bob"),
String::from("Carol"),
];
for name in &names {
println!("Hello, {}", name);
}
// names is still valid
println!("Processed {} names", names.len());

Common patterns for working with moves

Most move-related compiler errors fall into a few categories, each with established solutions.

Using a value after moving it is the most common error. When you pass a value to a function or assign it to another variable, the original binding becomes invalid.

let data = vec![1, 2, 3];
process(data);
// println!("{:?}", data); // Error: value borrowed after move

Three solutions exist depending on your needs. If you need multiple independent copies, clone before the move:

let data = vec![1, 2, 3];
process(data.clone());
println!("{:?}", data); // Works: data was not moved

If you only need read access, change the function to accept a reference:

fn process_ref(data: &Vec<i32>) {
println!("Processing {} elements", data.len());
}
let data = vec![1, 2, 3];
process_ref(&data);
println!("{:?}", data); // Works: data was borrowed, not moved

If multiple parts of your program need ownership simultaneously, consider reference counting:

use std::rc::Rc;
let data = Rc::new(vec![1, 2, 3]);
let data2 = Rc::clone(&data);
// Both data and data2 can be used

Moving out of a borrowed context occurs when attempting to take ownership of something accessed through a reference.

fn get_first(v: &Vec<String>) -> String {
v[0] // Error: cannot move out of borrowed content
}

The function receives a reference to the vector, not ownership. It cannot take ownership of elements because that would leave the original vector in an inconsistent state. Return a reference instead, or clone the value:

fn get_first_ref(v: &Vec<String>) -> &String {
&v[0]
}
fn get_first_owned(v: &Vec<String>) -> String {
v[0].clone()
}

Extracting values from Options and Results requires attention to ownership. The method unwrap() moves the inner value out, consuming the Option. The method as_ref() converts &Option<T> to Option<&T>, allowing inspection without consuming. The method take() on a mutable reference moves the value out and replaces it with None.

let mut opt = Some(String::from("hello"));
let value = opt.take();
// opt is now None, value is Some("hello")

Performance of moves

Developers coming from C++ often ask about the performance cost of moves. The answer is reassuring: moves are cheap. A move copies only the stack portion of a value, which for most types is a fixed small size regardless of how much data the type manages.

Moving a Vec<i32> with a million elements costs the same as moving a Vec<i32> with three elements: a copy of 24 bytes (pointer, length, capacity). The heap data does not move. This differs from C++ move semantics, where moving might involve pointer swapping and null assignments to leave the source in a valid-but-empty state. Rust’s moves are pure bitwise copies with compile-time invalidation of the source.

The compiler often optimizes away even these small copies. If the source variable is never used before the move, the compiler may eliminate the copy entirely and construct the value directly in its final location. This optimization, related to what C++ calls copy elision, happens automatically without programmer intervention.

The following diagram summarizes the decision process for handling values needed in multiple places:

graph TD
    Q["Need value in multiple places?"] -- No --> M["Move it (zero cost)"]
    Q -- Yes --> C["Consider alternatives"]
    C --> R["Read-only access?<br/>Use references"]
    C --> I["Need independent copies?<br/>Clone explicitly"]
    C --> S["Shared ownership?<br/>Use Rc or Arc"]

[!visual-conversion] Choosing between moves, references, clones, and reference counting. Print diagram (PDF 069, printed p. 67) recreated in Mermaid; decision tree, labels verbatim.

The mental model that proves useful: moves are free, clones have cost, and references have rules. When data is needed in multiple places, prefer references if the borrow checker permits them. Fall back to Rc/Arc for shared ownership without copying. Use clone() when independent copies are genuinely needed, and accept the cost knowingly.

Borrowing through references

Moving ownership for every use would be impractical. If you wanted to pass a string to a function for printing, you would lose access to it afterward. Borrowing solves this problem by allowing temporary access to a value without taking ownership. References are borrows: they provide read or write access to data owned by someone else.

Rust distinguishes between immutable references (&T) and mutable references (&mut T). The borrowing rules enforce two constraints that together prevent data races and dangling pointers.

First, at any given time, a value can have either one mutable reference or any number of immutable references, but not both simultaneously.

This rule directly prevents data races. A data race occurs when two threads access the same memory, at least one access is a write, and there is no synchronization. By requiring that mutable access be exclusive, Rust ensures that whenever mutation occurs, no other reference exists that could observe partially written data.

Second, references must always be valid. They cannot outlive the value they reference. The compiler tracks how long each reference is used and how long the referenced value lives, rejecting programs where a reference might outlive its referent. This prevents dangling pointers at compile time rather than through runtime checks or garbage collection.

The following diagram illustrates valid and invalid borrowing patterns:

graph TD
    O["Owner"]
    subgraph INV["Invalid Patterns"]
        I1["&T + &mut T<br/>(read during write)"]
        I2["Multiple &mut T<br/>(concurrent writes)"]
    end
    subgraph VAL["Valid Patterns"]
        V1["Multiple &T<br/>(shared reads)"]
        V2["Single &mut T<br/>(exclusive write)"]
    end
    O -- Rejected --> I1
    O -- Rejected --> I2
    O --> V1
    O --> V2

[!visual-conversion] Rust’s borrowing rules: valid and invalid reference patterns. Print diagram (PDF 071, printed p. 69) recreated in Mermaid; edges to the invalid patterns are labelled “Rejected” in print; edges to the valid patterns are unlabelled.

These rules initially feel restrictive, especially to developers accustomed to the flexibility of garbage-collected references. The restriction reveals its value when refactoring code or adding concurrency. Changes that would introduce data races fail to compile. Changes that would create dangling pointers fail to compile. The compiler becomes a collaborator that catches mistakes before they become bugs.

A common pattern involves borrowing for function calls. A function that needs to read data takes an immutable reference, and the caller retains ownership. After the function returns, the caller can continue using the value. A function that needs to modify data takes a mutable reference, and the caller temporarily gives up access until the function returns. These patterns appear throughout Rust code: functions declaring through their signatures exactly what access they require, and callers providing that access without permanently surrendering their data.

The borrowing rules also prevent iterator invalidation, a common source of bugs in C++. When iterating over a collection, you typically hold an immutable reference to the collection. The rules prevent simultaneously holding a mutable reference that could modify the collection (adding or removing elements) while iteration is in progress. What would be a subtle bug or undefined behavior in C++ becomes a compile error in Rust.

Lifetimes: how Rust tracks validity

Lifetimes are Rust’s mechanism for ensuring that references remain valid for as long as they are used. Every reference has a lifetime, the scope during which the reference is valid. Most of the time, the compiler infers lifetimes automatically, and you write references without annotation. When the compiler cannot determine the relationship between lifetimes, explicit annotations are required.

Lifetime annotations do not change how long a reference lives. They describe relationships between lifetimes that the compiler cannot infer, enabling it to verify that references remain valid. The syntax uses a tick followed by a name, like ‘a or ‘static, appearing after the ampersand in reference types.

The following diagram illustrates how lifetimes track reference validity:

graph TD
    subgraph OUTER["Outer Scope"]
        S1["let s1 = String::from('long')"]
        subgraph INNER["Inner Scope"]
            R["let r = &s2"]
            S2["let s2 = String::from('hi')"]
            OK["use r here: OK"]
        end
        ERR["use r here: ERROR"]
    end
    S1 --> INNER
    R -- "r's lifetime" --> OK
    R -- "s2 dropped" --> ERR

[!visual-conversion] Lifetimes track how long references remain valid; using a reference after its referent is dropped is a compile error. Print diagram (PDF 072, printed p. 70) recreated in Mermaid; nested scopes and edge labels as printed.

Functions returning references

Consider a function that takes two string references and returns a reference to the longer one:

fn longest(left: &str, right: &str) -> &str {
if left.len() > right.len() { left } else { right }
}

This code fails to compile with the error “missing lifetime specifier.” The compiler cannot determine how the output’s lifetime relates to the inputs. The function might return a or might return b, depending on runtime values. Without knowing which input the output borrows from, the compiler cannot verify that the returned reference remains valid.

The fix requires explicit lifetime annotations:

fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() > right.len() { left } else { right }
}

The ‘a annotation declares a lifetime parameter. Both inputs and the output share this lifetime, meaning:

  • left must live at least as long as ‘a
  • right must live at least as long as ‘a
  • The returned reference is valid for ‘a

At each call site, the compiler determines the concrete lifetime and verifies that the returned reference is not used after either input becomes invalid.

Divergent lifetimes

What happens when two inputs genuinely have different lifetimes? Consider a function where each input comes from a different scope:

fn pick_one<'a, 'b>(x: &'a str, y: &'b str) -> &str {
if x.len() > y.len() { x } else { y }
}

This also fails to compile. The return type has no lifetime annotation, and the compiler cannot determine whether the output borrows from x (lifetime ‘a) or y (lifetime ‘b).

Several solutions exist. The most common is to require both inputs to share a lifetime, as shown in the longest example. This works when callers can ensure both references remain valid for the same duration.

When inputs truly have independent lifetimes, the Cow (Clone on Write) type provides flexibility:

use std::borrow::Cow;
fn pick_one<'a, 'b>(x: &'a str, y: &'b str) -> Cow<'static, str> {
if x.len() > y.len() {
Cow::Owned(x.to_owned())
} else {
Cow::Owned(y.to_owned())
}
}

This version clones the data, producing an owned String wrapped in Cow. The ‘static lifetime indicates the result owns its data and has no lifetime constraints. The cost is heap allocation, but the function now works regardless of input lifetimes.

A middle ground uses Cow with borrowed data when possible:

use std::borrow::Cow;
fn pick_one<'a>(x: &'a str, y: &'a str) -> Cow<'a, str> {
if x.len() > y.len() {
Cow::Borrowed(x)
} else {
Cow::Borrowed(y)
}
}

Here, when both inputs share lifetime ‘a, the result borrows without cloning. The Cow type can later be converted to an owned String if needed, but avoids allocation in the common case.

Structs holding references

When a struct holds a reference, it must declare a lifetime parameter:

struct Holder<'a> {
data: &'a str,
}

The lifetime parameter ‘a ensures that Holder cannot outlive the data it references. Any instance of Holder<'a> is constrained to exist only while the referenced string remains valid.

fn main() {
let s = String::from("hello");
let h = Holder { data: &s };
println!("{}", h.data);
} // Safe: s lives long enough for h

Attempting to return a Holder that references local data fails:

fn bad_holder() -> Holder<'static> {
let s = String::from("temporary");
Holder { data: &s } // Error: s does not live long enough
}

The function declares it returns Holder<'static>, meaning the holder’s reference is valid for the entire program. But s is a local variable that is dropped when the function returns. The compiler catches this mismatch and rejects the code.

The following diagram shows how struct lifetimes constrain usage:

graph TD
    subgraph INV["Invalid: Data"]
        I1["let holder"] --> I2["{ let data = ...; holder = Holder { data: &data } }"] --> I3["data dropped here"] --> I4["use holder: DANGLING"]
    end
    subgraph VAL["Valid: Struct"]
        V1["let data = String::from(...)"] --> V2["let holder = Holder { data: &data }"] --> V3["use holder"] --> V4["holder dropped"] --> V5["data dropped"]
    end

[!visual-conversion] Structs with references must not outlive their referenced data. Print diagram (PDF 076, printed p. 74) recreated in Mermaid; two side-by-side flows. The second line of each panel title is hidden behind the first box in the print itself; only “Invalid: Data” / “Valid: Struct” are legible.

Lifetime elision rules

The compiler includes lifetime elision rules that allow many common patterns to omit explicit annotations. These rules cover predictable cases:

  • Each input reference gets its own lifetime parameter
  • If there is exactly one input lifetime, it is assigned to all output lifetimes
  • If there is a &self or &mut self parameter, its lifetime is assigned to all output lifetimes

When a function takes one reference and returns one reference, the compiler assumes they have the same lifetime:

fn first_word(s: &str) -> &str {
// Compiler infers: fn first_word<'a>(s: &'a str) -> &'a str
s.split_whitespace().next().unwrap_or("")
}

When a method takes &self and returns a reference, the compiler assumes the returned reference borrows from self:

impl Document {
fn title(&self) -> &str {
// Compiler infers the return borrows from self
&self.title
}
}

These rules cover most cases; explicit annotations appear primarily in complex data structures or when the compiler’s inference is insufficient.

The ‘static lifetime

The ‘static lifetime is a special case that means “valid for the entire program.” String literals have static lifetime because they are embedded in the program’s binary and never deallocated:

let s: &'static str = "I live forever";

Types that own all their data (like String, rather than &str) can satisfy static lifetime requirements because they do not reference external data. This distinction matters for thread spawning and other APIs that require ‘static bounds:

fn spawn_thread() {
let owned = String::from("owned data");
std::thread::spawn(move || {
// owned is moved into the closure, satisfying 'static
println!("{}", owned);
});
}

The closure captures owned by moving it, taking ownership. Since the closure owns the data rather than borrowing it, the closure satisfies ‘static requirements.

Common lifetime mistakes

Several patterns frequently cause lifetime errors for developers learning Rust:

Returning references to local variables is the most common mistake. A function that creates data internally cannot return a reference to it:

fn create_greeting() -> &str {
let s = String::from("hello");
&s // Error: returns reference to local variable
}

The solution is to return an owned type (String) instead of a reference.

Storing references with mismatched lifetimes occurs when a struct’s lifetime does not match the data it stores:

struct Cache<'a> {
data: &'a str,
}
fn build_cache() -> Cache<'static> {
let temp = String::from("temporary");
Cache { data: &temp } // Error: temp does not live long enough
}

The fix depends on requirements: either ensure the data outlives the struct, or have the struct own its data.

Confusing multiple lifetimes happens when assuming different inputs must share a lifetime. Sometimes they can, sometimes they cannot. When the relationship between inputs is genuinely independent, separate lifetime parameters or owned data may be necessary.

Capturing references across async boundaries introduces subtle issues covered in Chapter 19. Async functions are state machines, and references held across .await points must remain valid for the duration of the future. This constraint often requires owned data or careful structuring of async code.

RAII and deterministic destruction

Resource Acquisition Is Initialization (RAII) is a pattern familiar to C++ developers: resources are acquired in constructors and released in destructors. A file handle opens in the constructor and closes in the destructor. A mutex lock acquires in the constructor and releases in the destructor. The pattern ensures that resources are properly released regardless of how control flow exits a scope (normal return, early return, or exception).

Rust adopts this pattern but makes it more rigorous through the ownership system. When a value goes out of scope, its destructor runs. For types that manage resources, this means automatic cleanup. The Drop trait provides custom destructor logic for types that need cleanup beyond simple memory deallocation.

The Drop trait and ownership responsibility

The Drop trait defines a single method, drop, which Rust calls automatically when a value’s owner goes out of scope. This is not a method you call directly; the compiler inserts drop calls at the appropriate points. You implement Drop to specify what cleanup your type requires, and the ownership system ensures that cleanup happens exactly once, at exactly the right time.

The core principle is this: every owner is solely responsible for disposing what it owns. When an owner is dropped, everything it owns is dropped as well. This responsibility cannot be delegated, forgotten, or duplicated. The owner does not need to remember to clean up its resources; the act of going out of scope triggers cleanup automatically.

Consider a struct that owns several fields:

struct Connection {
socket: TcpStream,
buffer: Vec<u8>,
metadata: String,
}

When a Connection value is dropped, all three fields are dropped. The TcpStream closes its network connection. The Vec deallocates its heap buffer. The String deallocates its heap buffer. The Connection’s owner did not need to call cleanup methods on each field. Dropping the Connection triggered the entire chain of disposal.

The following diagram illustrates the disposal cascade when an owner goes out of scope:

graph TD
    subgraph OWN["Owner in Scope"]
        C["conn: Connection"] --> S["socket: TcpStream"]
        C --> B["buffer: Vec"]
        C --> M["metadata: String"]
    end
    subgraph END["Scope Ends:"]
        D1["1. Connection::drop() runs"] --> D2["2. TcpStream::drop()<br/>closes socket"]
        D1 --> D3["3. Vec::drop()<br/>frees buffer"]
        D1 --> D4["4. String::drop()<br/>frees string"]
    end
    subgraph AFTER["After Drop"]
        R["All resources released"]
    end
    OWN --> END --> AFTER

[!visual-conversion] When an owner drops, all owned resources are disposed in a cascade. Print diagram (PDF 081, printed p. 79) recreated in Mermaid; three stacked frames, numbering and labels verbatim.

The disposal cascade follows the ownership structure recursively. If the metadata String owns heap-allocated bytes, those bytes are freed when the String is dropped. If the Vec contains Strings, each String is dropped before the Vec’s own buffer is freed. The ownership tree determines the disposal tree.

Drop ordering

When multiple values go out of scope together, Rust drops them in a deterministic order. For variables within a scope, drops occur in reverse declaration order. The last variable declared is dropped first, then the second-to-last, and so on.

fn example() {
let first = String::from("first");
let second = String::from("second");
let third = String::from("third");
// When function returns:
// third drops, then second, then first
}

This reverse order matters when later variables might reference earlier ones. A reference to first stored in third would become dangling if first dropped before third. By dropping in reverse order, Rust ensures that references remain valid until their referents are no longer needed.

For struct and tuple fields, Rust drops fields in declaration order (first field drops first). However, well-designed types should not rely on specific drop ordering between their fields. If one field’s destructor depends on another field still being valid, the design likely has problems that the compiler cannot catch. Each field should be independently droppable.

The following diagram shows drop ordering in a scope with multiple variables:

graph TD
    subgraph FS["Function Scope"]
        A["let first = ..."] --> B["let second = ..."] --> C["let third = ..."]
    end
    subgraph DO["Drop Order"]
        D1["1. drop(third)"] --> D2["2. drop(second)"] --> D3["3. drop(first)"]
    end
    FS --> DO

[!visual-conversion] Variables drop in reverse declaration order when their scope ends. Print diagram (PDF 083, printed p. 81) recreated in Mermaid; labels verbatim.

Guaranteed execution

Unlike C++ destructors, Rust destructors are guaranteed to run in well-defined circumstances. There is no exception-safety concern in the traditional sense because Rust does not have exceptions that unwind through arbitrary code. When a function returns (normally or by propagating an error with the question mark operator), destructors run for all values going out of scope. Panics do unwind by default, running destructors along the way, but panics represent programming errors rather than expected failure modes.

This has profound implications for resource management. File handles close automatically when the File value goes out of scope. Mutex locks release automatically when the MutexGuard goes out of scope. Memory frees automatically when Box, Vec, or String values go out of scope. The patterns that C++ developers implement carefully with RAII and smart pointers are the default in Rust, enforced by the compiler rather than relying on programmer discipline.

A few edge cases exist where Drop might not run. Calling std::mem::forget explicitly prevents a value from being dropped, which is safe but potentially leaks resources. Creating reference cycles with Rc or Arc can prevent values from ever being dropped, since their reference counts never reach zero. Panics configured to abort rather than unwind skip destructor execution entirely. These cases are uncommon in typical code and are usually explicit choices rather than accidents.

Drop and borrowing interaction

The Drop trait interacts with the ownership system in important ways. A value can only be dropped by its owner, and only once. The compiler ensures that values are not dropped while still borrowed, preventing use-after-free bugs.

Consider the interaction between drops and borrows. If you have a vector and a reference to one of its elements, the compiler prevents clearing or dropping the vector while the reference exists. Doing so would leave a dangling reference, the very bug that Rust is designed to prevent. Only after the reference is no longer used can the vector be modified or dropped.

The following diagram shows how borrowing extends a value’s required lifetime:

graph TD
    subgraph TL["Timeline"]
        V1["vec created"] --> V2["&vec[0] borrowed"] --> V3["borrow ends"] --> V4["vec can be dropped"]
    end
    subgraph BL["Blocked"]
        X1["vec.clear()"]
        X2["vec.push(...)"]
        X3["drop(vec)"]
    end
    V2 -- prevents --> BL

[!visual-conversion] While a borrow exists, operations that would invalidate it are rejected. Print diagram (PDF 085, printed p. 83) recreated in Mermaid; the “Blocked” frame has a second title line that is hidden behind a box in the print itself and cannot be read.

This compile-time enforcement means that use-after-free bugs, one of the most common sources of security vulnerabilities in systems code, are structurally impossible in safe Rust. The ownership and borrowing rules work together to ensure that values are dropped only when no references to them remain.

Practical uses of Drop

The Drop trait is not limited to memory deallocation and resource cleanup. It provides a general mechanism for running code when a scope ends, regardless of how that scope ends. This capability enables patterns that would require try-finally blocks, context managers, or manual cleanup calls in other languages.

Consider timing how long a block of code takes to execute. A timer struct can record the start time when created and print the elapsed time when dropped:

struct Timer {
name: String,
start: Instant,
}
impl Timer {
fn new(name: &str) -> Self {
Timer {
name: name.to_string(),
start: Instant::now(),
}
}
}
impl Drop for Timer {
fn drop(&mut self) {
let elapsed = self.start.elapsed();
println!("{}: {:?}", self.name, elapsed);
}
}

Using this timer requires no explicit stop call. Creating the timer starts the clock; leaving the scope stops it:

fn process_data(data: &[u8]) {
let _timer = Timer::new("process_data");
// ... processing logic ...
// Timer prints elapsed time when function returns
}

The underscore prefix in _timer signals that the binding exists only for its side effects. The value is not used directly, but its existence keeps the timer alive until the scope ends. Whether the function returns normally, returns early, or propagates an error with the ? operator, the timer’s drop method runs and reports the elapsed time.

This pattern extends to any action that should occur when leaving a scope. A scope guard can ensure that a flag is reset, a counter is decremented, or a notification is sent:

struct ScopeGuard<F: FnOnce()> {
action: Option<F>,
}
impl<F: FnOnce()> Drop for ScopeGuard<F> {
fn drop(&mut self) {
if let Some(action) = self.action.take() {
action();
}
}
}

The guard stores a closure that runs when the guard is dropped. This enables ad-hoc cleanup actions without defining new types for each case. A function that temporarily modifies some state can use a guard to ensure the state is restored:

fn with_logging_enabled<R>(f: impl FnOnce() -> R) -> R {
set_logging(true);
let _guard = ScopeGuard {
action: Some(|| set_logging(false)),
};
f()
// Logging is disabled when _guard drops, even if f() panics
}

The following diagram illustrates how Drop enables automatic scope-based actions:

graph TD
    subgraph FS["Function Scope"]
        A["let _timer = Timer::new()"] --> B["... do work ..."] --> C["scope ends"]
    end
    C --> D["Timer::drop() runs"] --> E["Prints elapsed time"]

[!visual-conversion] Drop runs automatically when scope ends, enabling timers, guards, and cleanup actions. Print diagram (PDF 088, printed p. 86) recreated in Mermaid; labels verbatim.

Mutex guards in the standard library use this pattern. Calling mutex.lock() returns a guard that holds the lock. When the guard drops, the lock is released. There is no unlock() method to forget to call; leaving the scope releases the lock automatically. This design makes it difficult to accidentally hold a lock longer than intended and impossible to forget to release it.

Database transaction wrappers often use Drop to implement automatic rollback. The transaction object is created, work is performed, and if the transaction is not explicitly committed before the scope ends, the Drop implementation rolls back. Success paths call commit explicitly; error paths and panics trigger automatic rollback through Drop.

The key insight is that Drop transforms scope boundaries into execution points. Any action that should occur when leaving a scope, regardless of how the scope is exited, belongs in a Drop implementation. This pattern replaces scattered cleanup code with centralized, guaranteed execution.

The type system as guardian: Send and Sync

Thread safety in Rust extends from the ownership system through two marker traits: Send and Sync. A type is Send if ownership can be transferred between threads. A type is Sync if references to it can be shared between threads. Most types are both Send and Sync automatically; the compiler derives these traits based on a type’s contents.

Certain types deliberately lack these traits. Reference-counted pointers (Rc) are neither Send nor Sync because their reference count is not atomic. Interior mutability types like RefCell are Send but not Sync because their runtime borrow checking is not thread-safe. When you write concurrent code, these traits appear in function signatures as bounds, and the compiler rejects calls with types that fail to meet them.

This is where Rust’s safety guarantees converge. The ownership system ensures that values have exactly one owner. The borrowing system ensures that references are valid and that mutable access is exclusive. Send and Sync ensure that ownership transfers and reference sharing across threads maintain these invariants. Together, they make data races impossible in safe Rust code.

Chapter 17 explores these traits in detail, including how they interact with Arc, Mutex, and other concurrency primitives.

Stack vs heap: understanding Box, Rc, Arc

Rust makes memory allocation explicit in ways that garbage-collected languages abstract away. Understanding where values live and how they are accessed is essential for effective Rust programming, especially when coming from languages where the garbage collector manages all heap allocation invisibly.

By default, values in Rust live on the stack. Stack allocation is fast (adjusting the stack pointer takes a single instruction) and deallocation is automatic (the stack frame is popped when the function returns). Stack values have fixed size known at compile time, which enables this efficiency but limits flexibility.

Heap allocation is explicit, typically through smart pointer types. The most common are Box<T>, Rc<T>, and Arc<T>, each providing different ownership semantics for heap-allocated data.

Box: heap allocation with single ownership

Box<T> places a value on the heap with a pointer on the stack. It has single ownership semantics identical to regular values: when the box goes out of scope, the heap memory is freed. Box is the simplest smart pointer and the most efficient, adding only a single pointer indirection to heap-allocated data.

Boxes are useful in several situations. Recursive types require indirection because otherwise their size would be infinite (a type that contains itself would need infinite space). Trait objects require boxes (or other pointer types) because their concrete size is not known at compile time. Large values might be boxed to avoid expensive stack copies when moving, though Rust often optimizes moves to avoid copies regardless.

The most common use of Box is enabling recursive data structures. A linked list or tree node that contains another node of the same type cannot have a statically known size unless the contained node is behind a pointer. Box provides this indirection with clear ownership: each node owns its child nodes, and dropping the root drops the entire structure.

Rc: reference counting for shared ownership

Sometimes multiple parts of a program need to share ownership of the same data. Neither can outlive the other arbitrarily; both need the data to exist as long as either needs it. Rc<T> (Reference Counted) provides shared ownership through reference counting. Each clone of an Rc increments the count; each drop decrements it. When the count reaches zero, the value is deallocated.

Reference counting adds overhead: every clone and drop updates the count. This overhead is typically negligible but worth considering for performance-critical code with heavy cloning. More significantly, Rc prevents mutable access to the contained value. With multiple owners, allowing mutation would require synchronization or risk data races. Rc provides shared immutable access by default; interior mutability patterns (covered in later chapters) can provide controlled mutation when needed.

Rc is not thread-safe. Its reference count operations are not atomic, so sending an Rc to another thread could corrupt the count. The compiler prevents this by marking Rc as neither Send nor Sync. Attempting to share an Rc across threads produces a compile error, not a runtime bug.

Arc: Atomic reference counting

Arc<T> (Atomically Reference Counted) is the thread-safe equivalent of Rc. Its reference count operations use atomic instructions, making it safe to share across threads. The API is nearly identical to Rc, and the types can often be swapped when transitioning single-threaded code to concurrent code.

The atomic operations in Arc add overhead compared to Rc’s non-atomic operations. This overhead is small on modern hardware but measurable in tight loops. Prefer Rc for single-threaded code and Arc when sharing across threads.

Note that Arc provides shared ownership, not shared mutability. For shared mutable state across threads, Arc is typically combined with synchronization primitives like Mutex. Chapter 17 covers the Arc<Mutex<T>> pattern and other concurrency primitives in detail.

The following diagram summarizes when to use each smart pointer type:

Arc<T>Rc<T>Box<T>
Multiple ownersMultiple ownersSingle owner
Thread-safeSingle-threadedHeap allocation
Shared immutableShared immutableRecursive types

[!visual-conversion] Smart pointer types: Box for single ownership, Rc for shared single-threaded, Arc for shared multi-threaded. Print chart (PDF 092, printed p. 90) of three labelled columns of property boxes, recreated as a table; column order and cell text verbatim.

Choosing between these types reflects design decisions about ownership in your program. Single ownership is the common case and should be the default; prefer Box when heap allocation is needed without sharing. Rc applies when multiple parts of single-threaded code need shared access to long-lived data. Arc applies when sharing crosses thread boundaries. The type system guides these decisions by rejecting attempts to share Rc across threads or to use Arc where Rc would suffice (through convention and clippy lints, since Arc works in single-threaded code, it is merely less efficient).

Interior mutability

Rust’s borrowing rules enforce a fundamental constraint: you can have either one mutable reference or multiple immutable references, but never both simultaneously. This rule prevents data races and ensures memory safety, but it creates a puzzle. What if you need to mutate data through a shared reference? What if multiple parts of your program hold references to a value and one of them needs to modify it?

The standard library provides types that enable mutation through shared references by moving borrow checking from compile time to runtime. This pattern is called interior mutability because the mutation happens inside an outwardly immutable container. The container appears immutable to the type system (you access it through &T), but it allows controlled mutation of its contents.

Interior mutability is not an escape hatch from Rust’s safety guarantees. The borrowing rules still apply; they are simply enforced at a different time. Violating the rules at runtime causes a panic rather than undefined behavior. The program crashes predictably rather than corrupting memory silently.

Cell: mutation for Copy types

Cell<T> provides interior mutability for types that implement Copy.

The design is elegantly simple: rather than providing references to the interior value, Cell provides methods to get and set the value by copying it. This sidesteps the borrowing rules entirely because no reference to the interior ever exists. You copy the value out, work with the copy, and copy a new value back in.

This approach has important implications. Because values are copied rather than borrowed, Cell imposes no runtime tracking overhead. There are no reference counts to update, no borrow flags to check. The operations compile down to simple memory reads and writes.

However, this efficiency comes with a constraint: the contained type must implement Copy. Strings, vectors, and other heap-allocated types cannot be stored in Cell because copying them would be either expensive or semantically incorrect.

The following example demonstrates a counter that can be incremented through a shared reference:

use std::cell::Cell;
struct Counter {
value: Cell<u32>,
}
impl Counter {
fn new() -> Self {
Counter { value: Cell::new(0) }
}
fn increment(&self) {
let current = self.value.get();
self.value.set(current + 1);
}
fn get(&self) -> u32 {
self.value.get()
}
}

Notice that increment takes &self, not &mut self. In standard Rust, modifying a field would require &mut self, which would prevent multiple references from existing simultaneously. With Cell, the method can mutate the counter’s value through a shared reference. Multiple parts of a program can hold &Counter references, and any of them can call increment.

This pattern appears frequently in performance-sensitive code that needs to track statistics or maintain counters without threading mutable references through every function call. A logging system might count events through shared references. A parser might track line numbers while multiple components hold references to the parser state.

Cell provides no protection against concurrent access from multiple threads. Its operations are not atomic, and concurrent reads and writes would cause data races. The compiler enforces this by marking Cell as !Sync, which prevents sharing Cell references across thread boundaries. Within a single thread, Cell is perfectly safe because Rust’s single-threaded execution model prevents concurrent access. The copy semantics provide additional safety: because no reference to the interior value can exist (only copies), there is no possibility of a reference being invalidated by a mutation.

RefCell: runtime Borrow checking

RefCell<T> provides interior mutability for any type, not just Copy types. Where Cell sidesteps borrowing by copying values, RefCell embraces borrowing but moves the rule enforcement from compile time to runtime. This allows RefCell to work with types like String, Vec, or any custom struct, types that cannot or should not be copied.

The mechanism works by maintaining borrow state inside the RefCell. When you request a borrow, RefCell checks whether that borrow is permitted given the current state. If you request an immutable borrow while no mutable borrow is active, it succeeds. If you request a mutable borrow while any other borrow is active, RefCell panics. The same rules that the compiler enforces at compile time are now enforced by RefCell at runtime.

This runtime checking has a small cost. RefCell maintains a borrow counter (for immutable borrows) and a flag (for mutable borrows), and every borrow or release updates this state. The overhead is minimal for most applications, but it exists. More significantly, errors that the compiler would catch at compile time now become runtime panics. A bug in borrow logic that would prevent compilation with regular references instead crashes the program when it runs. This is still safe (no undefined behavior, no memory corruption), but it shifts error detection from development time to execution time.

The following example demonstrates a Document struct that allows modification through shared references:

use std::cell::RefCell;
struct Document {
content: RefCell<String>,
metadata: RefCell<Metadata>,
}
impl Document {
fn append(&self, text: &str) {
let mut content = self.content.borrow_mut();
content.push_str(text);
}
fn word_count(&self) -> usize {
let content = self.content.borrow();
content.split_whitespace().count()
}
}

The borrow() method returns a smart pointer type called Ref<T> that acts like an immutable reference &T. When the Ref is dropped (goes out of scope), the borrow is released. Similarly, borrow_mut() returns RefMut<T>, which acts like a mutable reference &mut T. These smart pointers implement Deref and DerefMut, so you can use them almost transparently as if they were regular references.

The borrowing rules apply exactly as they would at compile time, but violations cause panics rather than compilation errors. Multiple immutable borrows can coexist, just as multiple &T references can exist simultaneously. A mutable borrow requires exclusivity, just as &mut T requires no other references to exist. The difference is when the check happens:

let data = RefCell::new(vec![1, 2, 3]);
let borrow1 = data.borrow(); // OK: first immutable borrow
let borrow2 = data.borrow(); // OK: second immutable borrow
let borrow3 = data.borrow_mut(); // PANIC: cannot borrow mutably while immutably borrowed

This panic is intentional and represents a programming error. The code attempted to violate the borrowing rules, and RefCell caught the violation. In unsafe code or in languages without these checks, such a violation would cause undefined behavior, potentially corrupting memory or causing security vulnerabilities. RefCell converts this into a predictable, debuggable crash. The program fails loudly at the exact point of the error rather than continuing with corrupted state.

For situations where borrow conflicts are expected rather than erroneous, RefCell provides fallible alternatives. The try_borrow() method returns Result<Ref<T>, BorrowError>, and try_borrow_mut() returns Result<RefMut<T>, BorrowMutError>. These allow the program to detect and handle conflicts gracefully:

if let Ok(mut content) = document.content.try_borrow_mut() {
content.push_str(" additional text");
} else {
// Handle the case where content is already borrowed
}

This pattern is useful when borrow conflicts represent legitimate runtime conditions rather than bugs. A callback system might attempt to modify state that is currently being iterated; the try methods allow detecting and deferring the modification rather than panicking.

Like Cell, RefCell is not thread-safe. Its borrow tracking uses non-atomic operations that would be corrupted by concurrent access from multiple threads. The compiler prevents this by marking RefCell as !Sync. For thread-safe interior mutability, Rust provides Mutex (which blocks until exclusive access is available) and RwLock (which allows multiple readers or one writer), both covered in Chapter 17.

When to use interior mutability

Interior mutability is powerful but should be used judiciously. It moves checking from compile time to runtime, trading static guarantees for flexibility. This trade-off is sometimes necessary, but reaching for interior mutability as a first resort often indicates a design that could be restructured. The goal is not to avoid interior mutability entirely but to use it intentionally, understanding both its benefits and its costs.

The fundamental question to ask is: does the type system’s view of mutability match the conceptual view? Sometimes mutation is an implementation detail that should not be visible in the API. Sometimes multiple owners genuinely need to share and modify data. In these cases, interior mutability is the right tool. But when mutation could be expressed through the normal ownership model with some restructuring, that restructuring usually leads to clearer, more maintainable code.

Legitimate uses of interior mutability include:

Caching and memoization. A struct might cache computed results for performance. From the caller’s perspective, calling a method to get a result is a read operation; the fact that the struct internally caches that result is an implementation detail. The method should take &self because it does not modify any logically observable state. But the cache itself must be modified, which requires interior mutability.

This pattern is common enough that it has a name: the “internal mutability for caching” pattern. The external API presents an immutable interface while the implementation maintains mutable caches. The following example demonstrates a computation that caches its result after the first calculation:

struct ExpensiveComputation {
input: Vec<u32>,
cached_result: RefCell<Option<u64>>,
}
impl ExpensiveComputation {
fn result(&self) -> u64 {
if let Some(cached) = *self.cached_result.borrow() {
return cached;
}
let computed = self.input.iter().map(|&x| x as u64).sum();
*self.cached_result.borrow_mut() = Some(computed);
computed
}
}

The result method takes &self, signaling to callers that it does not modify the computation’s logical state. Internally, RefCell allows the cache to be populated on first access. Callers do not need to know about or manage this caching; it is purely an optimization.

Shared state in single-threaded contexts. GUI frameworks, event systems, and callback-heavy code often need multiple components to share mutable state. A button click handler might need to modify state that the main window also holds. An event listener might need to update state that other listeners read. Threading mutable references through all these components would require restructuring the entire application around borrow lifetimes.

Interior mutability provides an escape hatch. Components can hold shared references (through Rc) to state wrapped in RefCell, allowing any component to read or modify the state as needed. This pattern trades compile-time borrow checking for flexibility in how components interact. The trade-off is often worthwhile in event-driven architectures where the control flow makes static lifetime analysis impractical.

Breaking cycles in reference-counted graphs. When using Rc for graph structures (trees with parent pointers, doubly-linked lists, general graphs), the structure inherently involves shared ownership:

multiple nodes reference the same neighbor. Modification requires interior mutability because the shared Rc references provide only immutable access to their contents. This pattern is examined in detail in the next subsection.

Mock objects and test doubles. Test code sometimes needs to record method calls or return different values on successive calls. A mock object might need to track how many times a method was called while presenting an immutable interface to the code under test. Interior mutability allows the mock to record state internally through the same interface the production code uses.

Avoid interior mutability when restructuring would suffice. If you find yourself wrapping large portions of a struct in RefCell, step back and consider whether the ownership model could be redesigned. Often, passing &mut self through the call chain, restructuring data ownership, or splitting a struct into separately owned components eliminates the need for runtime borrow checking. The resulting code is usually clearer because mutation is explicit in the types rather than hidden behind interior mutability.

A useful heuristic: if interior mutability would make up more than a small fraction of a struct’s fields, the design probably needs rethinking. Interior mutability works best for isolated concerns like caches, counters, or lazily initialized values, not for the core mutable state of an object.

Combining Rc and RefCell

A common pattern combines Rc and RefCell to create shared mutable state: Rc<RefCell<T>>. Understanding why this combination is necessary requires thinking about what each type provides and what it lacks.

Rc alone provides shared ownership. Multiple parts of a program can hold Rc references to the same data, and the data lives until all references are dropped. However, Rc provides only immutable access to its contents. The Deref implementation for Rc returns &T, never &mut T. This is by design: with multiple owners, allowing one owner to mutate the data while another reads it would violate Rust’s borrowing rules.

RefCell alone provides interior mutability. Code with a &RefCell<T> can borrow the contents mutably, even though it only has a shared reference to the RefCell itself. However, RefCell does not provide shared ownership. If you have one RefCell and need multiple parts of our program to access it, you need to manage lifetimes carefully or restructure the code.

The combination Rc<RefCell<T>> provides both. The Rc handles shared ownership: clone the Rc to give another part of the program access to the same data. The RefCell handles mutability: call borrow_mut() to modify the data through any of those shared references. Together, they enable patterns that neither could support alone.

This combination appears frequently when modeling data structures that have inherent sharing. Graphs contain nodes with multiple edges pointing to them. Trees with parent pointers have nodes referenced by both their parent and their children. Observer patterns have subjects referenced by multiple observers. In all these cases, the structure of the data itself requires shared ownership, and the operations on that data require mutation.

The following example demonstrates a simple tree where nodes can have multiple children and any node can be modified:

use std::cell::RefCell;
use std::rc::Rc;
type SharedNode = Rc<RefCell<Node>>;
struct Node {
value: i32,
children: Vec<SharedNode>,
}
impl Node {
fn new(value: i32) -> SharedNode {
Rc::new(RefCell::new(Node {
value,
children: Vec::new(),
}))
}
fn add_child(parent: &SharedNode, child: SharedNode) {
parent.borrow_mut().children.push(child);
}
fn increment_all(node: &SharedNode) {
node.borrow_mut().value += 1;
for child in &node.borrow().children {
Node::increment_all(child);
}
}
}

The type alias SharedNode makes the pattern’s intent clear: this is a node that can be shared across the program. The new function returns a SharedNode rather than a plain Node, establishing from the start that nodes are meant to be shared. The add_child function demonstrates mutation through a shared reference: it takes &SharedNode (not &mut SharedNode) but modifies the node’s children. The increment_all function shows traversal with mutation, incrementing each node’s value while walking the tree.

Notice the careful handling in increment_all. The function borrows mutably to increment the value, then borrows immutably to iterate over children. These borrows do not overlap: the mutable borrow is released (the RefMut is dropped) before the immutable borrow begins. If the code tried to hold both borrows simultaneously, RefCell would panic. This is the runtime enforcement of Rust’s borrowing rules: the code compiles, but incorrect borrow patterns cause runtime failures.

This pattern has real costs that should influence when you use it. Every access requires going through two layers of indirection: first dereferencing the Rc to get the RefCell, then borrowing through the RefCell to get the data. The reference counting in Rc and the borrow tracking in RefCell both impose overhead, small but present. More significantly, borrow errors become runtime panics rather than compile-time errors. A mistake in borrow logic that would be caught by the compiler with regular references instead manifests as a crash when the code runs.

The code is also more complex to read and write. Calls to borrow() and borrow_mut() clutter the logic. The type Rc<RefCell<Node>> is more verbose than Node or &Node. These are ergonomic costs that accumulate across a codebase.

Use this pattern when the problem genuinely requires shared mutable ownership. Graph algorithms, certain UI architectures, and some concurrent data structures have inherent sharing that cannot be refactored away. In these cases, Rc<RefCell<T>> is the right tool. But do not reach for it as a workaround for borrow checker difficulties that could be solved through better design. Often, restructuring data ownership or passing mutable references through the call chain leads to code that is clearer, faster, and safer.

The following diagram illustrates the relationship between these interior mutability types:

Rc<RefCell<T>>RefCell<T>Cell<T>
Shared ownershipAny TT: Copy required
Shared mutabilityRuntime borrow trackingZero overhead
Single-threaded onlyborrow/borrow_mutget/set by value

[!visual-conversion] Interior mutability types: Cell for Copy types, RefCell for any type, Rc<RefCell> for shared mutable ownership. Print chart (PDF 105, printed p. 103) of three labelled columns of property boxes, recreated as a table; column order and cell text verbatim.

For thread-safe equivalents, Mutex<T> replaces RefCell<T> and Arc<Mutex<T>> replaces Rc<RefCell<T>>. The concepts are analogous, but the synchronization mechanisms differ. Chapter 17 covers these concurrent patterns in detail.

Core Concepts Covered

Rust’s foundational concepts form an interconnected system that provides safety guarantees without runtime overhead. Default immutability makes mutation explicit and visible in types, simplifying reasoning about code behavior and enabling safe concurrent sharing of immutable data.

The ownership system ensures every value has exactly one owner, enabling automatic memory management without garbage collection.

When ownership needs to be shared, move semantics transfer ownership to a new binding, invalidating the original.

Borrowing allows temporary access to values without ownership transfer. The borrowing rules (one mutable reference or multiple immutable references, but not both simultaneously) prevent data races at compile time. Lifetimes make reference validity explicit, enabling the compiler to reject programs that would create dangling pointers.

The Drop trait enables RAII patterns with guaranteed destructor execution, ensuring resources are released when their owners go out of scope. Smart pointers (Box, Rc, Arc) provide different ownership semantics for heap-allocated data, each with clear use cases and trade-offs.

Interior mutability through Cell and RefCell enables mutation through shared references by moving borrow checking to runtime. These types solve specific problems like caching and shared state in single-threaded contexts. The Rc<RefCell> pattern provides shared mutable ownership when the problem domain genuinely requires it.

The Send and Sync traits extend safety guarantees to concurrent code, ensuring that only thread-safe types can be transferred to or shared across threads. The compiler verifies these constraints at every thread boundary.

The next chapter examines how Rust’s structs, enums, and pattern matching replace the class hierarchies familiar from object-oriented programming. With the ownership model understood, these constructs reveal their full power for modeling domain concepts without null and without inheritance.