Languages and runtimesDive 04 of 06

Rust ownership: the checks and the machine

Follow a batch of log lines through moves, borrow checking, threads and async suspension. See what the compiler proves, what a future stores, and the instructions that remain.

Levels
8
Reading
42 min
Depth
Idea to Machine
Published

One owner. One responsibility for cleanup.

Can the old name
still read the logs?

A borrow lets another name look. A move hands over ownership. Change line 4 and watch the last line become illegal.

  1. let lines = vec![String::from("ERROR disk")];
  2. let view = &lines;
  3. println!("{}", view.len());
  4. let worker = &lines;
  5. println!("{}", lines.len());

Accepted: lines still owns the vector. Both shared references may read it.

rustc accepts this program.
The last use of view is on line 3.
The borrow on line 4 does not take ownership.

Exact move diagnostic captured with rustc 1.100.0 (0ef1bc386 2026-11-09), --edition=2024 --color=never --emit=metadata --cap-lints=allow. The capture adds drop(worker) to keep that binding used.

Level 01/08Idea

Who may touch these lines?

You have a batch of log lines in a Vec<String>. One function finds errors. Another appends a summary. A worker sends the batch elsewhere. The work sounds ordinary until you ask a precise question: what happens to a reference into the vector when someone changes or frees the storage behind it?

A vector can grow by allocating a larger buffer, moving its elements there and freeing the old buffer. An element is a String header, which in turn owns a UTF-8 buffer. A reference to an element points into the vector’s allocation. A string slice points into a String’s allocation. Which operation invalidates which address depends on exactly what you borrow. Treating every name as an independent handle to freely mutable storage hides these relationships.

Rust makes you express them. An owning value carries responsibility for its resources. A reference grants temporary access without taking that responsibility. The compiler checks whether the accesses can coexist and whether every referenced value remains alive. The result is memory safety without a tracing garbage collector in the language runtime. Allocation, deallocation and operating-system calls still happen; an ownership proof does not make resources cost nothing.

The familiar three rules are a useful entry point. Each ordinary owning value has one owner at a time. Access through references permits many shared &T borrows or an exclusive &mut T borrow to overlapping data. A reference must not be used beyond the lifetime of its referent. Shared ownership types and interior mutability add explicit protocols around these rules. The useful word is access: a dormant reference value does not necessarily keep its loan live until the closing brace.

Read the batch

Many readers

&lines → find_matches&lines → statistics

All may inspect the same allocation. None may invalidate it.

Change the batch

One exclusive access

&mut lines → push

The vector may reallocate. References into it cannot be used across this mutation.

End the batch

Owner drops the strings, then releases the vector’s backing storage

Any reference used afterward would point into dead storage. Borrow checking rejects that use before the program runs.

Reading, mutation and destruction need different permissions. Vec::push may relocate String headers, so existing element borrows must finish before it can run.

Three bugs from one missing relationship

A use-after-free happens when a reference is used after its storage has been released. A double free happens when two paths both believe they own the same allocation and release it twice. A data race involves conflicting concurrent memory accesses, at least one a write, without the synchronization the memory model requires. Ownership, borrowing and thread-safety traits address these problems together: who cleans up, who may access, and which permissions may cross a thread boundary.

Safe Rust can still deadlock, leak memory, produce wrong answers or panic on a bounds check. A program can also exhaust memory or deliberately keep values alive forever. These are distinct from dereferencing a dangling pointer or racing unsynchronized writes. Keeping that distinction makes the guarantee useful. You can trust a safe library interface to preserve memory safety while still reviewing its resource use and application logic.

Compare this with the Go collector. A tracing collector discovers which objects remain reachable and recovers unreachable storage. Rust usually decides cleanup from control flow and ownership transfers. Neither approach eliminates the need to reason about concurrency. Go’s garbage collector prevents a class of lifetime failures; it does not make simultaneous writes to an ordinary map safe. Rust adds static restrictions to what your references may do.

ApproachWho keeps storage alive?Where do you pay?
Manual allocationYour protocol pairs allocations and frees.Runtime allocation and cleanup; correctness rests on that protocol.
Tracing GCReachability from runtime roots.Tracing, bookkeeping, heap headroom and collection scheduling.
Rust ownershipOwners, checked borrows and explicit shared ownership.Compile-time checking; runtime allocation, destructors and chosen sharing mechanisms.

Our program will keep one batch through the whole descent. find_matches accepts a borrowed slice of Strings and returns views into matching lines. After those views’ last use, the program appends a line and moves the batch into a thread. Later we will replace the input step with an async fetch, parse its text and await an acknowledgement. The data changes hands; the question about valid access stays the same.

A slice parameter is deliberate. The search needs a sequence of Strings, not ownership of a growable allocation. Taking &[String] accepts a borrowed Vec through coercion and also works with other contiguous storage. Choosing the smallest useful permission gives callers more freedom. A function that only reads does not need &mut Vec<String>, and a function that does not keep the batch does not need to consume it.

Complete synchronous log pipeline · compiled and run, edition 2024
use std::sync::{Arc, Mutex};

pub struct Match<'a> {
    pub line: &'a str,
}

pub fn find_matches<'a>(lines: &'a [String], needle: &str) -> Vec<Match<'a>> {
    lines
        .iter()
        .filter(|line| line.contains(needle))
        .map(|line| Match {
            line: line.as_str(),
        })
        .collect()
}

fn main() {
    let mut lines = vec![String::from("INFO start"), String::from("ERROR disk")];
    let matches = find_matches(&lines, "ERROR");
    println!("{}", matches[0].line);
    lines.push(String::from("INFO done"));
    let worker = std::thread::spawn(move || find_matches(&lines, "ERROR").len());
    println!("worker: {}", worker.join().unwrap());

    let scoped = vec![String::from("ERROR scoped")];
    std::thread::scope(|scope| {
        scope.spawn(|| println!("scoped: {}", scoped.len()));
    });

    let count = Arc::new(Mutex::new(0_usize));
    let shared = Arc::clone(&count);
    std::thread::spawn(move || *shared.lock().unwrap() += 1)
        .join()
        .unwrap();
    println!("count: {}", *count.lock().unwrap());
}

Ownership is a protocol for access and cleanup that the compiler checks before the log processor runs.

Level 02/08Interface

Move the responsibility

Start with let worker = lines;. The assignment moves the Vec value. The new binding owns the vector; the old binding cannot be used as an initialized Vec. Rust has transferred responsibility for its resources. It has not cloned every log line, and it has not inserted a garbage-collector root update. If a later expression reads lines, the compiler reports E0382.

A A transfer of a value that leaves the source place uninitialized for subsequent use, unless the type is Copy. is a source-language operation. It does not prescribe a machine instruction. The Vec has a pointer, a length and a capacity; on our 64-bit target the default-allocator Vec occupies 24 bytes. Moving it may copy that small header between stack slots, pass it through registers or disappear when the optimizer reuses its storage. The backing allocation does not move just because the owner changes.

The Strings add another layer. The Vec’s contiguous allocation contains String values, each 24 bytes here, and each String refers to separately owned text storage. A Vec move transfers the ability to drop all of these resources. A Vec<String>::clone() instead clones the vector’s elements; the String clones own independent text buffers. This is why replacing every ownership error with .clone() can change a hot path’s allocation behavior substantially.

Moving this Vec transfers its header and ownership of the same allocations. These are logical field groups; Rust does not guarantee their ordering in memory.

Copy is a semantic promise

Small integers, booleans and shared references implement Copy. Assignment copies such a value and leaves the source usable. A type can be Copy only when its components permit it and it has no destructor. Bitwise duplication must preserve its meaning. Duplicating the bytes of an owning Vec while treating both copies as owners would let both destructors free the same storage, so Vec is not Copy.

Clone is a separate trait with an explicit method call. A String clone allocates independent text storage. An Rc::clone or Arc::clone makes another handle to shared storage and increments a count. A numeric clone can be as cheap as a copy. The trait name alone does not tell you whether the operation is deep, shallow, allocating or expensive; its implementation does.

An exclusive reference is not Copy. If you could freely duplicate &mut T and use both references independently, exclusivity would disappear. Rust commonly creates a shorter reborrow instead: a temporary exclusive access derived from the original. The parent reference becomes usable again after that access ends. This is one reason to think in permissions and live uses rather than count pointer-shaped values in the source.

Cleanup follows initialized ownership

Local variables normally drop in reverse declaration order when their scopes end. Struct fields drop in declaration order, after the struct’s own Drop implementation if it has one. A Vec drops its initialized elements and releases its backing allocation. Returning early and unwinding through a panic also need cleanup; aborting the process does not unwind. These rules make a destructor useful for locks and file handles as well as heap memory. The Reference specifies the drop scopes and ordering.

A move changes which place remains initialized. The source does not run a second destructor for the moved value. If only one branch moves a value, the compiler tracks initialization across the branches. It can encode that knowledge in separate cleanup paths or use drop flags when the state must be represented at runtime. A drop flag is not a permanent boolean attached to every object; it is a mechanism for the cases that require conditional cleanup.

Create lines

parent.lines
owns Vec
Vec allocation
owns String buffers

The allocations remain at their original addresses.

Borrow and search

parent.lines
owns Vec
Vec allocation
owns String buffers

matches: &str views · last use before transfer

Move to worker

parent.lines
moved
worker.lines
owns String buffers

The allocations remain at their original addresses.

Worker finishes

parent.lines
moved
worker.lines
dropped

One owner performed cleanup. No second free in the parent.

  1. lines owns the Vec. Its initialized elements own their UTF-8 buffers.
1 / 4
Trace the responsibility for this batch. References borrow access; moving into the worker transfers cleanup.

Partial moves make the distinction visible. Moving one non-Copy field out of a struct can leave the other fields available, while the whole struct is no longer available as an intact value. A type with a Drop implementation restricts moving its fields out, because its destructor expects the value to remain intact. The compiler’s initialization analysis works at the level of places and fields, not just variable names.

You can also choose to keep a resource alive. std::mem::forget consumes a value without running its destructor. Reference-counted cycles can keep allocations reachable through one another indefinitely. Safe Rust permits leaks, so unsafe code must not rely on a destructor inevitably running for soundness. Deterministic cleanup is the usual control-flow behavior, rather than a guarantee that all resources must eventually be reclaimed.

The header transfer in actual instructions

The function handoff below accepts and returns a Vec by value. We prevent inlining so its boundary stays visible. In the captured x86-64 assembly, a 16-byte load/store pair and an 8-byte load/store pair transfer the 24-byte header to the return destination. There is no loop over Strings and no allocation call. This is a concrete implementation of a move at this ABI boundary.

Input to the move capture · codegen.rs
#[unsafe(no_mangle)]
#[inline(never)]
pub fn handoff(lines: Vec<String>) -> Vec<String> {
    lines
}

rustc 1.100.0 (0ef1bc386 2026-11-09) · x86_64-unknown-linux-gnu · edition 2024 · target-cpu=x86-64

Actual handoff assembly · --emit=asm -C opt-level=3
handoff:
	.cfi_startproc
	movq	%rdi, %rax
	movq	16(%rsi), %rcx
	movq	%rcx, 16(%rdi)
	movups	(%rsi), %xmm0
	movups	%xmm0, (%rdi)
	retq
Check yourselfAfter let worker = lines, where are the log text buffers?

A move transfers responsibility. A copy preserves the source. A clone does whatever the type’s cloning protocol requires.

Level 03/08Interface

Loans live through their uses

The search should leave the batch with its caller. It borrows the Vec as a slice, reads the strings and returns matches that refer to their text. While those references will be used again, the caller must preserve the relevant storage and access permissions. The compiler calls these constraints lifetimes, but a lifetime is not a runtime countdown and a borrow is not a reference-count increment.

Rust’s borrow checker works over MIR, a control-flow representation of the function. It reasons about places, moves, borrows and uses. A lifetime inferred from the control-flow points at which a reference must remain valid, rather than simply the lexical block around its binding., or NLL, allow a loan to finish when its uses finish. A binding may remain in scope afterward. That is why the pipeline can print the matches, then mutate lines without putting the search inside an extra block.

In a straight-line example, “from creation to last use” is a helpful picture. In a function with branches and loops, a region is a set of control-flow points constrained by all relevant paths. Returning a reference can impose relationships across the function boundary. A destructor that may inspect a borrowed value can extend what must remain valid. The braces alone cannot answer these questions, and a simple text scan is not a general borrow checker.

Try moving push before the last read a in the experiment. The read needs the shared loan at a later point, so that loan crosses the mutation. Move the read earlier and the same mutation becomes legal. The row spacing represents program order; it does not suggest that a loan gradually fades or that a certain number of milliseconds must pass.

Supported language

share a / unique a borrow the whole Vec. read a calls a.len(); write a calls a.push(). push and len use the owner. Names: a, b, c, declared once. Up to 24 lines. No branches, reborrows, moves, projections or implicit two-phase borrows.

Rejected. Line 2: push conflicts with share loan a, used on line 3.

1. share aa · shared
2. pusha · shared
3. read aa · shared

Each row is one program point, equally spaced. A band includes creation and the final use. The model’s accept/reject results are tested against rustc on 168 generated programs.

fn check() {
  let mut lines = vec![String::from("ERROR disk")];
  let a = &lines;
  lines.push(String::from("INFO"));
  std::hint::black_box(a.len());
}
Edit a small language of Vec accesses and inspect the inferred loans. The generated Rust beside the result makes every supported command concrete.

Lend an exclusive reference, then use it again

The parent x already grants exclusive access to the Vec. Passing &mut *x creates a shorter exclusive reborrow of the same data. While the child access is needed, the parent cannot access that data independently. Once the helper returns, its child borrow ends and x is usable again. After the final use of x, the owner lines becomes usable too.

This is a transfer of access for a smaller region, without copying an exclusive reference. Calls often insert the reborrow implicitly; the explicit &mut *x makes the relationship visible here.

reborrow.rs · complete accepted program
fn append_summary(lines: &mut Vec<String>) {
    lines.push(String::from("INFO summary"));
    println!("child borrow: {} lines", lines.len());
}

fn main() {
    let mut lines = vec![String::from("ERROR disk")];
    let x = &mut lines;
    append_summary(&mut *x);
    x.push(String::from("INFO parent resumed"));
    println!("parent borrow after return: {} lines", x.len());
    println!("owner after final use of x: {} lines", lines.len());
}
Actual stdout · child access, then parent access, then owner access
child borrow: 2 lines
parent borrow after return: 3 lines
owner after final use of x: 3 lines
Use the parent before the child’s last use: E0499
reborrow-conflict.rs · rejected program
fn main() {
    let mut lines = vec![String::from("ERROR disk")];
    let x = &mut lines;
    let child = &mut *x;
    x.push(String::from("INFO parent too early"));
    println!("child used later: {}", child.len());
}
Exact rustc stderr · parent and child would overlap
error[E0499]: cannot borrow `*x` as mutable more than once at a time
 --> reborrow-conflict.rs:5:5
  |
4 |     let child = &mut *x;
  |                 ------- first mutable borrow occurs here
5 |     x.push(String::from("INFO parent too early"));
  |     ^ second mutable borrow occurs here
6 |     println!("child used later: {}", child.len());
  |                                      ----- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0499`.

A loan can be needed on only one branch

The next function borrows the first line before the if. Only the read branch uses that reference. The append branch has no later use of it, so that branch can mutate the vector. Both paths then join and inspect the vector’s length. The checker analyzes the function for either value of show; it does not need to guess which branch a caller will choose.

branch.rs · both control-flow paths compile
fn inspect_or_append(show: bool) {
    let mut lines = vec![String::from("ERROR disk")];
    let first = &lines[0];
    if show {
        println!("read branch: {first}");
    } else {
        lines.push(String::from("INFO appended"));
        println!("append branch: {} lines", lines.len());
    }
    println!("after join: {} lines", lines.len());
}

fn main() {
    inspect_or_append(true);
    inspect_or_append(false);
}
Actual stdout · execute both branch choices
read branch: ERROR disk
after join: 1 lines
append branch: 2 lines
after join: 2 lines

Add a print through first after the push on the append branch and the proof changes. That path now needs the loan across the mutation, so rustc rejects it with E0502. The difference is a use on one control-flow path, rather than a new lexical scope. These branch and reborrow examples go beyond the straight-line visualizer’s declared language.

Use first after appending on the same branch: E0502
branch-conflict.rs · rejected program
fn inspect_or_append(show: bool) {
    let mut lines = vec![String::from("ERROR disk")];
    let first = &lines[0];
    if show {
        println!("read branch: {first}");
    } else {
        lines.push(String::from("INFO appended"));
        println!("borrow now used on append branch: {first}");
    }
}

fn main() {
    inspect_or_append(false);
}
Exact rustc stderr · later use keeps this path’s loan live
error[E0502]: cannot borrow `lines` as mutable because it is also borrowed as immutable
 --> branch-conflict.rs:7:9
  |
3 |     let first = &lines[0];
  |                  ----- immutable borrow occurs here
...
7 |         lines.push(String::from("INFO appended"));
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
8 |         println!("borrow now used on append branch: {first}");
  |                                                      ----- immutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.

rustc 1.100.0 (0ef1bc386 2026-11-09) · x86_64-unknown-linux-gnu. Each fixture: rustc --edition=2024 --color=never -Dwarnings <name>.rs -o <name>. Accepted programs were run; rejected programs exited with status 1.

The error points to a conflicting access

E0499 reports overlapping exclusive borrows. In the first fixture, both a and b are exclusive references to the entire vector and both are used. E0502 reports a shared and an exclusive access that overlap. Our E0502 fixture takes a reference to an element, calls push and then prints through the reference. Even if today’s capacity would avoid reallocation, the method’s &mut self contract requires exclusive access.

E0505 prevents moving an owner while a borrow is still needed. Calling drop(lines) consumes the vector; the later print would use data that has been freed. E0506 prevents replacing a borrowed value, which would drop the old value. E0597 rejects a reference used after its owner’s scope ends. E0716 identifies a temporary owner dropped at the end of a statement while a derived reference is still needed. These are different routes to losing a valid referent.

The diagnostics show both ends of the relationship. Read the “borrow occurs here” location together with “later used here.” Moving a line can change whether there is a conflict, even when the offending expression itself is unchanged. Often the smallest fix is to finish the read sooner or return an owned result from a narrow part of the program. The correct fix depends on whether you want a view, a snapshot or a transfer of ownership.

Complete input · edition 2024

fn main() {
    let mut lines = vec![String::from("ERROR")];
    let a = &mut lines;
    let b = &mut lines;
    a.push(String::new());
    b.push(String::new());
}

Exact compiler stderr

error[E0499]: cannot borrow `lines` as mutable more than once at a time
 --> E0499.rs:4:13
  |
3 |     let a = &mut lines;
  |             ---------- first mutable borrow occurs here
4 |     let b = &mut lines;
  |             ^^^^^^^^^^ second mutable borrow occurs here
5 |     a.push(String::new());
  |     - first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0499`.

E0499: Two writers. Source and exact diagnostic shown.

rustc 1.100.0 (0ef1bc386 2026-11-09) · rustc --edition=2024 --color=never <code>.rs --emit=metadata --cap-lints=allow. Warnings suppressed for these intentionally invalid fixtures.

Real compiler diagnostics for six classic borrow failures. Each fixture is complete; the right panel preserves the compiler’s exact stderr.

Two-phase borrows explain a common surprise

Some calls reserve an exclusive borrow before activating it. For example, lines.push(format!("count={}", lines.len())) can read the length while evaluating the argument, then exclusively mutate the Vec when push runs. A reserved two-phase borrow permits certain shared accesses before activation. The shared length read is finished when push needs exclusive access.

Writing an explicit &mut lines into an ordinary argument does not automatically gain this behavior. Two-phase borrowing applies to particular compiler-generated implicit borrows. It also does not allow an exclusive reference to remain active while another access mutates the same data. The compiler guide lists reservation and activation rules. The small visualizer above uses explicit whole-vector borrows, so it has no reservation phase.

What Polonius changes

Some sound programs have been rejected because the checker loses precision about how lifetime relationships vary across branches. A function may return a reference in one branch and need to mutate in the other. Polonius improves the analysis of loans and their propagation. It changes which proofs the compiler can discover; it does not insert a runtime borrow manager into the executable.

The Rust team enabled Polonius Alpha on nightly in August 2026 for testing ahead of stabilization. That announcement distinguishes Alpha’s flow-sensitive outlives analysis from the original formulation. The 2026 project goal tracks the stabilization work. The announcement’s branch-sensitive HashMap example still produces E0499 on the Rust 1.100.0 compiler used here. The examples on this page use the established NLL subset; Polonius Alpha’s expanded acceptance remains nightly behavior in this comparison.

The checker follows the uses that need a loan. Shortening that need often removes the conflict without changing the data.

Level 04/08Interface

Put the relationship in the signature

The caller and the search function compile separately. The caller should not need to inspect the implementation to discover where returned references come from. The signature must describe that relationship. In find_matches, each returned Match points into the input lines. It does not point into the search needle, which is used only while deciding which lines match.

The lifetime parameter 'a ties the borrowed lines to the returned matches. It says the function can produce views valid for the chosen borrow of the input. It does not make the lines live longer. The caller chooses a region that fits its actual values and uses; the checker verifies that the owner outlives it. The body must uphold the signature for callers that satisfy its requirements.

The lifetime relationship in the compiled pipeline
use std::sync::{Arc, Mutex};

pub struct Match<'a> {
    pub line: &'a str,
}

pub fn find_matches<'a>(lines: &'a [String], needle: &str) -> Vec<Match<'a>> {
    lines
        .iter()
        .filter(|line| line.contains(needle))
        .map(|line| Match {
            line: line.as_str(),
        })
        .collect()
}

A signature constrains which region contains the other

lines allocation is alive
'a · lines borrowed

find_matches(&lines, needle)

Match<'a> → &'a str inside one String

Last use of every returned match

Mutation or drop may happen after the loans end

Nested boxes show an outlives constraint, not physical storage. No lifetime field is stored inside Match.

Every returned Match borrows from a line. Its usable lifetime must fit inside the lifetime of that storage, and later mutation must wait for the loans’ last uses.

A Match<'a> contains a string slice. On this target &str is 16 bytes: a data pointer and a byte length. There is no third field containing 'a, no timestamp and no runtime lookup from that name to the owner. The lifetime distinguishes legal uses of values that have the same runtime shape. A Vec of Match values owns its array of views while borrowing the text behind those views.

This design makes a useful promise and imposes a useful constraint. Producing a match does not clone a log line. Keeping the match means keeping the borrowed storage valid. If a queue must hold a match after the source batch is discarded, the queue needs ownership of the relevant text or some other owning handle. An owned String in the result may be the correct design there. Lifetimes expose the choice; they cannot remove the need to make it.

Elision removes spelling, not relationships

Rust lets you omit lifetime names in many signatures. Each elided input reference gets its own lifetime parameter. If there is exactly one input lifetime, that lifetime is assigned to elided output references. For methods with a reference receiver, the receiver’s lifetime is assigned to elided output lifetimes. These rules cover common APIs such as borrowing a prefix of one input string or returning a view into self.

Our search has two borrowed inputs. Without more information, the compiler cannot know whether a returned view borrows from lines, needle or both. Naming 'a on lines and the output expresses the intended source. Giving the needle that same lifetime would impose an unnecessary relationship on callers. A signature is part of the permission budget: overly broad constraints can make a safe implementation needlessly difficult to use.

Changing a lifetime annotation cannot rescue a function that returns a slice of a local String. The local is still dropped on return. A struct containing a reference to a local has the same problem. E0597 and E0716 point to this mismatch between an owner’s real lifetime and a reference’s required use. Returning the String itself, or borrowing from caller-owned storage, changes the actual ownership relationship.

'static and variance

A reference with lifetime 'static can refer to storage valid for the whole program, such as a string literal. A bound T: 'static means the type contains no borrowed data with a shorter lifetime. An owned String can satisfy that bound and still be dropped a moment later. The bound restricts borrowed contents; it does not make the owning value immortal.

Shared references are covariant in their lifetime: a reference known to remain valid for longer can be used where a shorter valid lifetime is needed. Exclusive references are also covariant in their own borrowing lifetime, but invariant in the referent type T. Those are separate parameters of &'a mut T. Saying simply “mutable references are invariant” misses the distinction.

Consider an exclusive reference to a slot containing a &'static str. If you could treat that slot as holding an arbitrary short-lived &str, you could write a reference to a local String into it. The original caller would then read the slot believing its contents were static. Invariance prevents the substitution that would make this write possible. The Reference’s variance table separates the outer lifetime from the referent type.

Complete input · edition 2024

fn main() {
    fn overwrite(slot: &mut &'static str) {
        let local = String::from("ERROR");
        *slot = local.as_str();
    }
    let mut text = "INFO";
    overwrite(&mut text);
}

Exact compiler stderr

error[E0597]: `local` does not live long enough
 --> variance.rs:4:17
  |
3 |         let local = String::from("ERROR");
  |             ----- binding `local` declared here
4 |         *slot = local.as_str();
  |         --------^^^^^---------
  |         |       |
  |         |       borrowed value does not live long enough
  |         assignment requires that `local` is borrowed for `'static`
5 |     }
  |     - `local` dropped here while still borrowed

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0597`.

variance: Writing through an invariant T. Source and exact diagnostic shown.

rustc 1.100.0 (0ef1bc386 2026-11-09) · rustc --edition=2024 --color=never <code>.rs --emit=metadata --cap-lints=allow. Warnings suppressed for these intentionally invalid fixtures.

The compiler refuses to write a local string slice into a slot promised to hold a static slice. The local lifetime cannot satisfy the slot’s type.
Check yourselfWhat does 'a add to the runtime representation of Match<'a>?

A lifetime annotation describes where a reference may come from and how long it may be used. It never extends the owner’s life.

Level 05/08Runtime

Move a check into runtime

Suppose several parts of the log processor share a cache. You want a method taking &self to update a cached count. Ordinary shared references do not permit arbitrary mutation of their referents. Rust provides types with carefully controlled Mutation supported through a shared reference by a type whose implementation maintains the required safety invariants. for this situation. Each type explains how mutation remains safe.

Cell<T> moves values in and out rather than handing out references to its inner value. For Copy values, get returns a copy; set replaces the stored value. RefCell<T> supports borrowing the inner value and tracks outstanding guards at runtime. It permits multiple shared guards or one exclusive guard. Dropping a guard releases its permission. A conflicting borrow call panics; try_borrow returns an error.

The runtime experiment uses the fallible protocol so you can deliberately cause conflicts without stopping the page. Acquire two readers, try a writer, release both readers, then try the writer again. The logical compatibility rule resembles the static borrow rule. The difference is when the rule can be decided and where a conflict is reported. A RefCell does not convert conflicting access into legal access; it detects the conflict while the program runs.

RefCell<Vec<String>> · try_borrow / try_borrow_mut

UnsafeCell<Vec>“ERROR disk”
Outstanding guards

None

Unborrowed. A shared or an exclusive borrow can succeed.

A bounded model of guard compatibility: at most eight shared guards. try_borrow returns an error on conflict; borrow would panic. Actual RefCell internals also handle guard splitting and counter overflow.

RefCell guards keep runtime borrows active until they are dropped. A guard’s last source-code read alone does not release the runtime borrow flag.

That last difference matters. NLL can end a static reference loan after its last necessary use, but a Ref guard has a destructor that updates runtime state. Keeping the guard in scope can keep the RefCell borrowed. Use a narrow block or explicitly drop the guard before attempting an incompatible borrow. A long-lived cache read guard can therefore block a write even when the programmer has finished reading its contents.

UnsafeCell is the foundation

UnsafeCell<T> marks memory that may be mutated through shared references. It relaxes the shared-reference immutability guarantee for that contained memory. Cell, RefCell, Mutex and atomic types build controlled interfaces around this capability. Simply casting an ordinary shared reference into a writable pointer does not grant the same permission. The marker belongs to the storage and the abstraction around it.

UnsafeCell does not relax exclusive-reference uniqueness, and it does not synchronize threads. Its low-level get method exposes a raw pointer; the implementation must still avoid dangling accesses, invalid values and data races. The UnsafeCell contract is the boundary between “mutation through sharing is permitted here” and “this particular mutation is safe.” Those are different obligations.

Reference counting solves another problem. Rc<T> shares ownership in one thread. Cloning a handle increments a non-atomic strong count; dropping the last strong handle destroys T. Weak handles can observe whether a strong owner remains without keeping T alive. They are useful for back-links that would otherwise form strong-reference cycles. Reference counting is deterministic bookkeeping, not a tracing cycle collector.

Arc<T> uses atomic reference counts so owning handles can participate in cross-thread sharing under its trait bounds. It does not make all inner operations thread-safe. An Arc of a mutable cell is not automatically a concurrently mutable container. Pairing it with a Mutex adds an access protocol; pairing it with immutable data may need no lock. The atomics dive follows the hardware cost behind this synchronization.

ToolWhat it controlsConflict or cost
&mut TStatic exclusive access.Invalid overlap rejected during compilation.
Cell<T>Value replacement through sharing.No borrowed inner reference exposed by its value accessors.
RefCell<T>Single-thread borrowing through guards.Runtime flag checks; error or panic on conflict.
Rc / ArcShared lifetime of an allocation.Reference-count updates; cycles can leak.
Mutex<T>Synchronized access through a lock guard.Lock operations, possible waiting and deadlock.

Unsafe does not suspend the language’s contract

Unsafe code can dereference raw pointers and perform other operations whose safety the compiler cannot establish. The programmer must uphold their preconditions. The borrow checker still applies to ordinary references inside an unsafe block. The boundary is an obligation to prove the missing facts, such as alignment, initialization, valid aliasing and allocation lifetime. A safe public method must preserve these facts for every input its signature accepts.

Miri interprets MIR and can detect many undefined behaviors on the paths it executes: use-after-free, invalid values, misaligned access, out-of-bounds access and data races, among others. It also checks experimental aliasing models. The Miri documentation inspected for this page describes Stacked Borrows as the default and -Zmiri-tree-borrows as the alternative. These models help test unsafe code; neither replaces the stable language’s evolving specification with a blanket proof from one successful test run.

Tree Borrows is an aliasing model for what executing programs may do, not another name for the compiler’s Polonius analysis. The compiler may reject a program statically before any aliasing model would execute it. Conversely, unsafe pointer operations can compile and then violate an execution rule. Keeping static acceptance, runtime checks and undefined behavior distinct prevents a great deal of confusion around unsafe Rust.

Interior mutability chooses a concrete protocol for shared mutation. Unsafe implementations must make that protocol safe for their callers.

Level 06/08System

Carry the proof across a thread

The batch is ready to send to a worker. std::thread::spawn(move || ...) puts the captured Vec into the closure. The closure becomes its owner and the parent can no longer read the old binding. Moving the owner does not relocate the strings’ heap allocations. It changes which thread may reach them through that ownership path and which execution eventually drops them.

Two auto traits govern this boundary. Send means a value can be transferred to another thread safely. Sync means shared references to a value can be transferred safely; equivalently, T: Sync when &T: Send. Structs generally acquire these properties from their fields, subject to explicit implementations and exceptions. The compiler checks these trait bounds at the spawn call. There is no runtime “Send” tag inside the vector.

Vec of String is Send because its contained values and allocator permit the transfer. RefCell is not Sync because its ordinary borrow bookkeeping does not synchronize concurrent calls through shared references. Rc is neither Send nor Sync: another Rc handle could remain on the old thread and race its non-atomic count. Merely promising that a closure is move does not turn either type into something else.

Parent thread

lines

Owns Vec<String>

move closure
TransferVec<String>: Send

The old binding becomes unusable. The allocation stays put.

Worker thread

closure.lines

Find matches, return a count, then drop the vector.

JoinHandle<usize>
Sharing a mutable count insteadArc handle → Mutex<usize> ← Arc handle

Arc keeps the allocation alive. Mutex mediates access and synchronizes threads. Neither role replaces the other.

A move closure transfers ownership under Send. For a shared mutable counter, Arc manages lifetime while Mutex manages access.

Move is not a lifetime extension

An ordinary spawned thread may outlive the function that started it, so its closure must satisfy a static lifetime bound. Moving a borrowed reference into the closure transfers the reference value, not ownership of the referent. If that reference points into a local Vec, the local still cannot disappear while the thread might use it. The fact that you intend to call join shortly afterward is not encoded in spawn’s lifetime contract.

std::thread::scope provides a different contract. Scoped threads finish before the scope returns, including through its cleanup behavior. They can borrow non-static local data that remains valid for that scope. The pipeline uses a scoped thread to read a second batch without transferring it. You can split a mutable slice into disjoint pieces and lend each piece to a worker; exclusive access to distinct data is compatible.

Shared mutable state requires a suitable protocol. The example wraps a usize count in Arc<Mutex<usize>>. Each Arc handle participates in ownership. The Mutex guard permits exclusive access to the count while holding the lock. Dropping the guard unlocks it. The lock also provides synchronization, which matters for the visibility and ordering of accesses across threads. An integer’s small size does not make unsynchronized shared mutation safe.

The deliberately invalid example below tries to share a RefCell between scoped threads. Its lifetime is long enough; that is not the failed proof. The shared reference would need Send, which requires the RefCell to be Sync. The compiler reports E0277 because it cannot satisfy that property. Choosing scoped threads solves a lifetime relationship, while choosing Mutex solves a synchronization relationship.

Complete input · edition 2024

fn main() {
    let lines = std::cell::RefCell::new(vec![String::from("ERROR")]);
    std::thread::scope(|s| {
        s.spawn(|| lines.borrow_mut().push(String::new()));
        lines.borrow_mut().push(String::new());
    });
}

Exact compiler stderr

error[E0277]: `RefCell<Vec<String>>` cannot be shared between threads safely
 --> E0277.rs:4:17
  |
4 |         s.spawn(|| lines.borrow_mut().push(String::new()));
  |           ----- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `RefCell<Vec<String>>` cannot be shared between threads safely
  |           |
  |           required by a bound introduced by this call
  |
  = help: the trait `Sync` is not implemented for `RefCell<Vec<String>>`
  = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
  = note: required for `&RefCell<Vec<String>>` to implement `Send`
note: required because `lines` is used within this closure
 --> E0277.rs:4:20
  |
4 |         s.spawn(|| lines.borrow_mut().push(String::new()));
  |                    ^^^^^
note: required by a bound in `Scope::<'scope, 'env>::spawn`
 --> /rustc/0ef1bc386059596dada8fb65b50425aab2ea637a/library/std/src/thread/scoped.rs:201:4

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.

E0277: Shared mutable cell across threads. Source and exact diagnostic shown.

rustc 1.100.0 (0ef1bc386 2026-11-09) · rustc --edition=2024 --color=never <code>.rs --emit=metadata --cap-lints=allow. Warnings suppressed for these intentionally invalid fixtures.

The compiler rejects an unsynchronized RefCell shared between threads. The error follows the Sync requirement through the captured reference.

Send and Sync are unsafe traits to implement manually. Library code may rely on them when transferring values or sharing references. An incorrect implementation can make safe callers execute undefined behavior, so “the fields compile” is not a sufficient review for an unsafe wrapper around raw pointers. The Rustonomicon explains the traits’ safety meaning and why the common exceptions need different protocols.

Memory safety also leaves application-level concurrency questions open. Two correct locks can be acquired in opposite orders and deadlock. An atomic counter can be used with an ordering too weak for a larger protocol. A worker can perform work twice or lose a notification. Ownership removes invalid access patterns from the design space; it does not prove the higher-level algorithm. The next boundary, async suspension, makes that distinction especially visible.

Send governs transfer, Sync governs sharing, and a lifetime bound governs how long borrowed data remains valid. Each answers a different question.

Level 07/08System

A suspended function is a value

Now fetch a batch, count matching lines and wait for an acknowledgement before processing the next source. A blocking function would keep its stack frame while waiting. An async function instead returns a future: a value implementing a protocol for making progress. Calling it creates that value. Its body starts running when the future is polled.

The Future trait’s poll method receives a pinned mutable reference to the future and a Context containing a Waker. It returns Poll::Ready(output) when complete, or Poll::Pending when it must yield. A pending operation arranges for the task to be woken when progress becomes possible. The executor decides when to poll the task again. Waking schedules an opportunity to resume; it does not resume the function inside the wake call.

The capture uses two controlled Gate futures. The first returns a log string when marked ready. The second acknowledges the computed count. A harness marks each gate ready and explicitly signals the waker; it performs no network I/O. A real socket future must register the current waker with its readiness machinery so completion can wake the right task. Both versions expose the same Pending/Ready boundary to their parent future.

Compiled async body · controlled fetch and acknowledgement gates
async fn fetch_and_parse(
    source: &'static str,
    fetch: Arc<AtomicBool>,
    flush: Arc<AtomicBool>,
) -> usize {
    let text = Gate {
        ready: fetch,
        value: Some(source),
    }
    .await;
    let count = {
        let lines: Vec<String> = text.lines().map(str::to_owned).collect();
        lines.iter().filter(|line| line.contains("ERROR")).count()
    };
    Gate {
        ready: flush,
        value: Some(()),
    }
    .await;
    count
}

Save exactly what must survive suspension

The compiler turns the function into a state machine. Conceptually it has a created state holding arguments, an awaiting-fetch state holding the fetch child, an awaiting-flush state holding the count and flush child, and a completed state. These are useful enum-like variants for understanding the transformation. The real compiler chooses its own discriminants, field ordering, overlap and cleanup representation; it does not promise this exact handwritten enum layout.

On the first poll, the body starts and polls the fetch child. If that child returns Pending, the parent saves enough state to resume there and returns Pending too. When fetch becomes ready, a later parent poll obtains text, allocates Strings, finds the count and drops the lines inside the block. It then polls the flush child during that same call. An await does not necessarily yield: it yields only if its child is pending.

The count survives the second suspension; the temporary Vec does not. At the next ready flush poll, the parent returns the count and becomes complete. Dropping a suspended future cancels it by dropping the fields live in its current state. Cleanup follows that state’s initialized values. If the state holds a network operation or a guard, its destructor behavior is part of cancellation. Cancellation does not automatically undo effects already performed elsewhere.

  1. 0Created
  2. 1AwaitFetch
  3. 2AwaitFlush
  4. 3Complete
Batch
1 / 2
Poll calls
0
Child ready?
No

Logical values saved in this state

Arguments: source + fetch readiness Arc + flush readiness Arc; body has not run

Batch future's poll result

Not polled

Not polled. Creating a future has not executed its body.

Manual polling of two separate fetch_and_parse futures, matching the captured synchronous harness. Waking marks the pending child ready. Create next batch future constructs a new future after the first one completes.

Manually drive two separate batch futures through their two awaits. Each Ready value belongs to one batch future; the Create next batch future control constructs the second one.

This widget manually drives two separate batch futures. The enclosing async loop continues within the same poll when a batch completes and returns Ready only with the final total.

The compiled loop awaits each batch sequentially
async fn process_loop() -> usize {
    let mut total = 0;
    for source in ["ERROR disk\nERROR retry", "INFO start\nERROR disk"] {
        let ready = Arc::new(AtomicBool::new(true));
        total += fetch_and_parse(source, ready.clone(), ready).await;
    }
    total
}

Poll the enclosing loop itself

In the original process_loop above, every gate starts ready. Its first outer poll runs both batches and returns Ready(3). To see suspension at each boundary, this second harness gives each batch its own fetch gate and flush gate, all initially pending. A gate saves the executor’s waker when polled. Completing that specific gate takes the registered waker and schedules the next outer poll.

Follow outer poll 3 in the real trace: the first flush returns Ready, the loop adds 2, constructs batch 2 and polls its fetch, all within that one call. The new fetch returns Pending, so the outer poll returns Pending. Only outer poll 5 returns Ready(3). The trace also runs an always-ready configuration to check the original example’s first-poll behavior.

Controlled process_loop · each batch has independent readiness gates
async fn process_loop(gates: &[[Switch; 2]; 2]) -> usize {
    let mut total = 0;
    for (i, source) in ["ERROR disk\nERROR retry", "INFO start\nERROR disk"]
        .into_iter()
        .enumerate()
    {
        let count = fetch_and_parse(source, i + 1, &gates[i]).await;
        total += count;
        println!("  batch {} complete: count={count}, total={total}", i + 1);
    }
    total
}
Actual executor trace · inner progress and the outer future’s poll results
poll outer 1
  batch 1 fetch: Pending
outer poll 1: Pending
complete batch 1 fetch
executor scheduled: wake 1
poll outer 2
  batch 1 fetch: Ready
  batch 1 flush: Pending
outer poll 2: Pending
complete batch 1 flush
executor scheduled: wake 2
poll outer 3
  batch 1 flush: Ready
  batch 1 complete: count=2, total=2
  batch 2 fetch: Pending
outer poll 3: Pending
complete batch 2 fetch
executor scheduled: wake 3
poll outer 4
  batch 2 fetch: Ready
  batch 2 flush: Pending
outer poll 4: Pending
complete batch 2 flush
executor scheduled: wake 4
poll outer 5
  batch 2 flush: Ready
  batch 2 complete: count=1, total=3
outer poll 5: Ready(3)
always-ready gates, matching the original process_loop setup
  batch 1 fetch: Ready
  batch 1 flush: Ready
  batch 1 complete: count=2, total=2
  batch 2 fetch: Ready
  batch 2 flush: Ready
  batch 2 complete: count=1, total=3
always-ready outer poll: Ready(3)

rustc 1.100.0 (0ef1bc386 2026-11-09) · x86_64-unknown-linux-gnu. rustc --edition=2024 --color=never -Dwarnings outer-loop.rs -o outer-loop; ./outer-loop. Readiness is controlled locally; the harness performs no network I/O.

Read the complete instrumented executor and gate implementation
outer-loop.rs · complete compiled source
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};

#[derive(Default)]
struct GateState {
    ready: bool,
    waker: Option<Waker>,
}

type Switch = Arc<Mutex<GateState>>;

struct Gate<T> {
    switch: Switch,
    value: Option<T>,
    batch: usize,
    operation: &'static str,
}

impl<T: Unpin> Future for Gate<T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
        let ready = {
            let mut state = self.switch.lock().unwrap();
            if !state.ready {
                state.waker = Some(cx.waker().clone());
            }
            state.ready
        };
        println!(
            "  batch {} {}: {}",
            self.batch,
            self.operation,
            if ready { "Ready" } else { "Pending" }
        );
        if ready {
            Poll::Ready(self.value.take().unwrap())
        } else {
            Poll::Pending
        }
    }
}

async fn fetch_and_parse(source: &'static str, batch: usize, gates: &[Switch; 2]) -> usize {
    let text = Gate {
        switch: gates[0].clone(),
        value: Some(source),
        batch,
        operation: "fetch",
    }
    .await;
    let count = {
        let lines: Vec<String> = text.lines().map(str::to_owned).collect();
        lines.iter().filter(|line| line.contains("ERROR")).count()
    };
    Gate {
        switch: gates[1].clone(),
        value: Some(()),
        batch,
        operation: "flush",
    }
    .await;
    count
}

async fn process_loop(gates: &[[Switch; 2]; 2]) -> usize {
    let mut total = 0;
    for (i, source) in ["ERROR disk\nERROR retry", "INFO start\nERROR disk"]
        .into_iter()
        .enumerate()
    {
        let count = fetch_and_parse(source, i + 1, &gates[i]).await;
        total += count;
        println!("  batch {} complete: count={count}, total={total}", i + 1);
    }
    total
}

#[derive(Default)]
struct Executor {
    scheduled: AtomicUsize,
}

impl Wake for Executor {
    fn wake(self: Arc<Self>) {
        let count = self.scheduled.fetch_add(1, Ordering::Relaxed) + 1;
        println!("executor scheduled: wake {count}");
    }
}

fn complete(switch: &Switch, label: &str) {
    println!("complete {label}");
    let waker = {
        let mut state = switch.lock().unwrap();
        state.ready = true;
        state
            .waker
            .take()
            .expect("gate must have registered a waker")
    };
    waker.wake();
}

fn poll_outer(future: Pin<&mut impl Future<Output = usize>>, waker: &Waker, number: usize) {
    println!("poll outer {number}");
    let result = future.poll(&mut Context::from_waker(waker));
    println!("outer poll {number}: {result:?}");
}

fn main() {
    let executor = Arc::new(Executor::default());
    let waker = Waker::from(executor.clone());
    let gates: [[Switch; 2]; 2] = std::array::from_fn(|_| {
        std::array::from_fn(|_| Arc::new(Mutex::new(GateState::default())))
    });
    let mut future = Box::pin(process_loop(&gates));
    poll_outer(future.as_mut(), &waker, 1);
    for (i, label) in [
        "batch 1 fetch",
        "batch 1 flush",
        "batch 2 fetch",
        "batch 2 flush",
    ]
    .into_iter()
    .enumerate()
    {
        complete(&gates[i / 2][i % 2], label);
        assert_eq!(executor.scheduled.load(Ordering::Relaxed), i + 1);
        poll_outer(future.as_mut(), &waker, i + 2);
    }

    println!("always-ready gates, matching the original process_loop setup");
    let ready: [[Switch; 2]; 2] = std::array::from_fn(|_| {
        std::array::from_fn(|_| {
            Arc::new(Mutex::new(GateState {
                ready: true,
                waker: None,
            }))
        })
    });
    let mut always_ready = Box::pin(process_loop(&ready));
    let result = always_ready.as_mut().poll(&mut Context::from_waker(&waker));
    println!("always-ready outer poll: {result:?}");
}

The loop creates and awaits one fetch-and-parse future at a time. Awaiting in a loop does not create parallel requests by itself. A task scheduler can interleave this loop with other tasks while it is pending, but starting multiple operations requires explicitly constructing and driving them concurrently. Joining, spawning or buffering several futures changes both the execution and the amount of live state.

Libraries such as Tokio provide executors, timers and I/O integration. Exactly how a task is scheduled and what a socket future stores depends on that library and its version. The standard Future and Waker interfaces define the boundary without requiring a particular executor. Moving CPU-heavy parsing into an async function does not make it yield automatically; a long uninterrupted parse still monopolizes the thread running poll.

A large local can become a large future

A local that must remain alive across an await needs storage in the suspended value. The two functions below perform the same 4096-byte local-buffer setup, but only one needs the buffer after suspension. In holding, the reference passed to black_box after await forces the buffer to remain available. In released, the buffer’s block ends before the await and only its computed length survives.

Both functions compiled · size measured on the unpolled future values
async fn holding() -> usize {
    let buffer = [7_u8; 4096];
    std::future::pending::<()>().await;
    std::hint::black_box(&buffer).len()
}

async fn released() -> usize {
    let len = {
        let buffer = [7_u8; 4096];
        std::hint::black_box(&buffer).len()
    };
    std::future::pending::<()>().await;
    len
}

Actual size_of_val · future storage before polling

buffer across await4097 B
buffer scope ends first16 B

Linear byte scale, zero to 4097. The 16-byte bar is intentionally tiny. rustc 1.100.0 (0ef1bc386 2026-11-09), x86-64, --edition=2024, default opt-level=0. Layout depends on compiler and target.

Actual future sizes from size_of_val, on a common zero-based linear scale. Keeping the array across suspension reserves space inside every future value.

The difference is a storage consequence, not a measurement of resident heap memory. A future value can live on a stack, be embedded inside another future or be boxed by a runtime. size_of_val measures that value’s inline representation. An owned Vec in a future contributes its header to the inline size while keeping its elements in a separate allocation. A Box similarly adds indirection rather than erasing the underlying allocation.

A future generally reserves enough space for its largest suspension state, with layout reuse possible between values that cannot be live together. The exact size includes alignment, discriminants and saved arguments chosen by this compiler. It can change when the compiler improves or when the target changes. The useful method is to measure your concrete future type and inspect which locals are live across awaits before guessing which field caused the growth.

Why poll takes Pin

An ordinary function can borrow a local array, await while the borrow remains live, then use the reference. In a suspended future, the array and the reference may both need to live inside the same value. Moving that value’s bytes to another address after the relationship is established could leave the saved reference pointing at the old location. This is a self-reference problem, rather than an allocation ownership problem.

Pin<P> provides a contract that keeps the pointee at a stable location until it is dropped, for types that need this guarantee. A Pin<Box<F>> can move as a pointer-sized handle while its boxed F stays put. Pinning can also be done on the stack; a heap allocation is not the definition of pinning. Types implementing Unpin permit the ordinary movable behavior even through Pin.

Moving a pointer handle and moving its pointee are different operations. A future with a saved reference into itself needs the pointee’s address to stay stable.

Compiler-generated async futures generally require pinning to poll. They can be moved before being pinned; constructing the future is not what establishes every internal address-sensitive relationship. Polling is the boundary where the implementation may establish one. Safe Pin APIs restrict moving pinned data out, while unsafe code that constructs or projects pins must uphold the promise. The pin module documentation explains both stable addresses and the associated drop guarantee.

Thread traits also reappear. An executor that moves suspended tasks across workers may require a Send future. A non-Send value such as Rc held across an await can make the containing future non-Send. A non-Send temporary whose scope finishes before suspension may be fine. Looking at the fields of suspension states connects an otherwise mysterious trait error directly to the saved value that cannot cross the thread boundary.

Check yourselfFetch becomes ready and calls the task’s Waker. What executes next?

A future is owned state plus a poll protocol. Locals live across awaits become storage, cleanup obligations and thread-safety constraints.

Level 08/08Machine

The proof disappears. Its consequences stay.

What remains of these permissions once the compiler emits machine code? A lifetime parameter has no runtime representation. A normal shared or exclusive reference does not carry a borrow counter. The borrow checker has already established whether the source program satisfies its rules. The executable retains the addresses and lengths needed to do useful work, along with cleanup and any runtime protocols you selected.

MIR makes the middle of the descent visible. The capture below comes from choose_drop, which either moves lines into another local or keeps the original owner until cleanup. Notice the move into a local, reference-taking for len, branches and explicit drop terminators. The compiler has represented responsibility as control flow. You can follow which initialized value is dropped on each path.

Source for the cleanup capture
pub fn choose_drop(lines: Vec<String>, take: bool) -> usize {
    if take {
        let moved = lines;
        moved.len()
    } else {
        lines.len()
    }
}

rustc 1.100.0 (0ef1bc386 2026-11-09) · x86_64-unknown-linux-gnu · edition 2024 · target-cpu=x86-64

Actual choose_drop MIR · --emit=mir -C opt-level=0
fn choose_drop(_1: Vec<String>, _2: bool) -> usize {
    debug lines => _1;
    debug take => _2;
    let mut _0: usize;
    let _3: std::vec::Vec<std::string::String>;
    let mut _4: &std::vec::Vec<std::string::String>;
    let mut _5: &std::vec::Vec<std::string::String>;
    let mut _6: bool;
    scope 1 {
        debug moved => _3;
    }

    bb0: {
        _6 = const false;
        _6 = const true;
        switchInt(copy _2) -> [0: bb3, otherwise: bb1];
    }

    bb1: {
        _6 = const false;
        _3 = move _1;
        _4 = &_3;
        _0 = Vec::<String>::len(move _4) -> [return: bb2, unwind: bb6];
    }

    bb2: {
        drop(_3) -> [return: bb4, unwind: bb10];
    }

    bb3: {
        _5 = &_1;
        _0 = Vec::<String>::len(move _5) -> [return: bb11, unwind: bb10];
    }

    bb4: {
        switchInt(copy _6) -> [0: bb5, otherwise: bb8];
    }

    bb5: {
        return;
    }

    bb6 (cleanup): {
        drop(_3) -> [return: bb10, unwind terminate(cleanup)];
    }

    bb7 (cleanup): {
        resume;
    }

    bb8: {
        drop(_1) -> [return: bb5, unwind continue];
    }

    bb9 (cleanup): {
        drop(_1) -> [return: bb7, unwind terminate(cleanup)];
    }

    bb10 (cleanup): {
        switchInt(copy _6) -> [0: bb7, otherwise: bb9];
    }

    bb11: {
        goto -> bb4;
    }
}
Real stable --emit=mir output at opt-level=0. MIR still has reference operations; it has no runtime lifetime timer or general borrow-check function.

This is a human-readable compiler dump, not a stable interchange format. Local numbering, block shape and drop elaboration can change between toolchains. Borrow checking itself runs on a suitable MIR form with its own inference data; emitted MIR is not a printout of every proof fact. Later lowering removes the need to represent source-language lifetime regions, while preserving the behavior of pointer operations and destructors.

Permissions become optimization facts

Erasing the proof does not erase its consequences. In the LLVM signature for bump, the exclusive count reference becomes a pointer argument with a noalias attribute. The other argument is readonly in this function. These facts help the optimizer reason that writing count cannot change the value loaded through other. The optimized assembly loads other once, doubles it and adds the result to count.

The compiled exclusive-reference example
#[unsafe(no_mangle)]
#[inline(never)]
pub fn bump(count: &mut usize, other: &usize) {
    *count += *other;
    *count += *other;
}

rustc 1.100.0 (0ef1bc386 2026-11-09) · x86_64-unknown-linux-gnu · edition 2024 · target-cpu=x86-64

Actual optimized bump signature · --emit=llvm-ir -C opt-level=3
define void @bump(ptr noalias nofree noundef align 8 captures(none) dereferenceable(8) %count, ptr noalias nofree noundef readonly align 8 captures(none) dereferenceable(8) %other) unnamed_addr #1 !guid !21 {
Actual bump assembly · two additions share one load of other
bump:
	.cfi_startproc
	movq	(%rsi), %rax
	addq	%rax, %rax
	addq	%rax, (%rdi)
	retq
Real optimized LLVM IR and assembly. noalias is an optimizer contract about accesses through the argument, not an extra instruction executed on entry.

The exact mapping from Rust references to LLVM attributes has a history. Rust disabled mutable-reference noalias after LLVM miscompilations, and the 2021 re-enablement work targeted LLVM 12 and newer. The captured IR establishes what this toolchain emits today. The lesson is to inspect the generated artifact and its flags; a language guarantee and a backend’s successful exploitation of that guarantee are separate layers.

Unsafe code must uphold the access rules even when a test happens to produce the expected instruction sequence. Violating an aliasing promise can let an optimizer reuse a load that you expected to change. “The processor executed the obvious memory writes” is not a valid model once the compiler is entitled to assume those writes cannot overlap. Undefined behavior breaks the assumptions under which the program was transformed.

A bounds-checked language can emit a loop without bounds checks

The hot loop sums the byte lengths of the log Strings. Iterating a slice tells the compiler exactly which elements belong to it. The optimized function walks String headers and accumulates their lengths. It does not inspect the UTF-8 text and does not allocate. In the main unrolled loop, four length fields are read per iteration, followed by a small remainder path. The accesses advance in 24-byte header strides.

Iterator input to the hot-loop capture
#[unsafe(no_mangle)]
#[inline(never)]
pub fn sum_lengths(lines: &[String]) -> usize {
    lines.iter().map(String::len).sum()
}

rustc 1.100.0 (0ef1bc386 2026-11-09) · x86_64-unknown-linux-gnu · edition 2024 · target-cpu=x86-64

Actual sum_lengths assembly · --emit=asm -C opt-level=3
sum_lengths:
	.cfi_startproc
	testq	%rsi, %rsi
	je	.LBB3_1
	movl	%esi, %ecx
	andl	$3, %ecx
	cmpq	$4, %rsi
	jae	.LBB3_4
	xorl	%edx, %edx
	xorl	%eax, %eax
	jmp	.LBB3_7
.LBB3_1:
	xorl	%eax, %eax
	retq
.LBB3_4:
	movabsq	$576460752303423484, %rax
	andq	%rax, %rsi
	leaq	16(%rdi), %r8
	xorl	%edx, %edx
	xorl	%eax, %eax
	.p2align	4
.LBB3_5:
	addq	(%r8), %rax
	addq	24(%r8), %rax
	addq	48(%r8), %rax
	addq	72(%r8), %rax
	addq	$4, %rdx
	addq	$96, %r8
	cmpq	%rdx, %rsi
	jne	.LBB3_5
	testq	%rcx, %rcx
	je	.LBB3_9
.LBB3_7:
	leaq	(%rdx,%rdx,2), %rdx
	leaq	(%rdi,%rdx,8), %rdx
	addq	$16, %rdx
	shll	$3, %ecx
	leaq	(%rcx,%rcx,2), %rcx
	xorl	%esi, %esi
	.p2align	4
.LBB3_8:
	addq	(%rdx,%rsi), %rax
	addq	$24, %rsi
	cmpq	%rsi, %rcx
	jne	.LBB3_8
.LBB3_9:
	retq
Actual optimized sum_lengths assembly. Loop-control comparisons remain, but there is no per-index bounds-panic branch or allocation call.

A loop comparison is not automatically a bounds check. Here the comparisons control iteration count and the remainder. An independent checked index into an unrelated slice might still need a panic path. The optimizer needs enough information to prove each access lies within the allocation. Writing iterator code often supplies that information clearly, but there is no rule that every iterator must vectorize or every index must remain checked.

The same distinction applies to the search. Ownership adds no borrow-table lookup to each String read, but substring matching still has real computational work. Building a Vec of matches can allocate. Cloning strings can allocate and copy text. Arc updates atomic counters. RefCell checks its runtime borrowing state. Mutex may wait. An async executor stores tasks and schedules polls. These costs belong to mechanisms the program actually chose.

Rust’s “zero-cost abstraction” claim is useful when it means that an abstraction can compile to the work a direct implementation requires, without a mandatory separate bookkeeping layer merely for expressing it. It is not a claim that the program performs no bookkeeping. Our vector header transfer is cheap; dropping the batch still walks and frees owned allocations. Our future has no hidden coroutine thread stack; it still needs enough storage for its live states.

The Zig comptime dive follows another way source-level structure disappears into specialized output. The V8 dive follows a runtime that gathers evidence and revises optimized code. Rust’s ownership path makes access relationships explicit and proves them ahead of execution. All three routes reward the same habit: follow a concrete program all the way to its real emitted artifact.

We can now account for the log batch at every boundary. One owner holds the vector. Search borrows produce views constrained by the lines’ storage. NLL lets mutation follow the views’ last use. A move closure transfers cleanup under Send. An async body saves only the state needed across pending operations, with Pin protecting address-sensitive relationships. At the bottom, the CPU sees loads, stores, branches, calls and synchronization chosen by the program. The compile-time proof is gone; the permitted behavior remains.

rustc 1.100.0 (0ef1bc386 2026-11-09)
rustc --edition=2024 --crate-type=lib --emit=mir -C opt-level=0 -C target-cpu=x86-64 codegen.rs -o codegen.mir
rustc --edition=2024 --crate-type=lib --emit=llvm-ir -C opt-level=3 -C target-cpu=x86-64 codegen.rs -o codegen.ll
rustc --edition=2024 --crate-type=lib --emit=asm -C opt-level=3 -C target-cpu=x86-64 codegen.rs -o codegen.s
rustc --edition=2024 -Dwarnings async.rs -o async
./async
Read the complete compiled async harness and captured output
async.rs · complete source, no external dependencies
use std::future::Future;
use std::pin::Pin;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
use std::task::{Context, Poll, Wake, Waker};

struct Noop;
impl Wake for Noop {
    fn wake(self: Arc<Self>) {}
}

struct Gate<T> {
    ready: Arc<AtomicBool>,
    value: Option<T>,
}
impl<T: Unpin> Future for Gate<T> {
    type Output = T;
    fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<T> {
        if self.ready.load(Ordering::Acquire) {
            Poll::Ready(self.value.take().unwrap())
        } else {
            Poll::Pending
        }
    }
}

async fn fetch_and_parse(
    source: &'static str,
    fetch: Arc<AtomicBool>,
    flush: Arc<AtomicBool>,
) -> usize {
    let text = Gate {
        ready: fetch,
        value: Some(source),
    }
    .await;
    let count = {
        let lines: Vec<String> = text.lines().map(str::to_owned).collect();
        lines.iter().filter(|line| line.contains("ERROR")).count()
    };
    Gate {
        ready: flush,
        value: Some(()),
    }
    .await;
    count
}

async fn holding() -> usize {
    let buffer = [7_u8; 4096];
    std::future::pending::<()>().await;
    std::hint::black_box(&buffer).len()
}

async fn released() -> usize {
    let len = {
        let buffer = [7_u8; 4096];
        std::hint::black_box(&buffer).len()
    };
    std::future::pending::<()>().await;
    len
}

async fn process_loop() -> usize {
    let mut total = 0;
    for source in ["ERROR disk\nERROR retry", "INFO start\nERROR disk"] {
        let ready = Arc::new(AtomicBool::new(true));
        total += fetch_and_parse(source, ready.clone(), ready).await;
    }
    total
}

fn main() {
    use std::mem::{size_of, size_of_val};
    println!("Vec<String>: {}", size_of::<Vec<String>>());
    println!("String: {}", size_of::<String>());
    println!("&str: {}", size_of::<&str>());
    println!("&mut usize: {}", size_of::<&mut usize>());
    println!("holding future: {}", size_of_val(&holding()));
    println!("released future: {}", size_of_val(&released()));
    println!("loop future: {}", size_of_val(&process_loop()));
    let waker = Waker::from(Arc::new(Noop));
    let mut cx = Context::from_waker(&waker);
    for source in ["ERROR disk\nERROR retry", "INFO start\nERROR disk"] {
        let fetch = Arc::new(AtomicBool::new(false));
        let flush = Arc::new(AtomicBool::new(false));
        let mut future = Box::pin(fetch_and_parse(source, fetch.clone(), flush.clone()));
        println!("fetch future: {}", size_of_val(future.as_ref().get_ref()));
        println!("{:?}", future.as_mut().poll(&mut cx));
        println!("{:?}", future.as_mut().poll(&mut cx));
        fetch.store(true, Ordering::Release);
        waker.wake_by_ref();
        println!("{:?}", future.as_mut().poll(&mut cx));
        flush.store(true, Ordering::Release);
        waker.wake_by_ref();
        println!("{:?}", future.as_mut().poll(&mut cx));
    }
}
Actual stdout · size measurements and manually driven poll trace
Vec<String>: 24
String: 24
&str: 16
&mut usize: 8
holding future: 4097
released future: 16
loop future: 152
fetch future: 80
Pending
Pending
Pending
Ready(2)
fetch future: 80
Pending
Pending
Pending
Ready(1)
support.rs · valid hero, two-phase call, clone and RefCell checks
use std::cell::RefCell;

fn main() {
    let mut lines = vec![String::from("ERROR disk")];
    let view = &lines;
    println!("{}", view.len());
    let worker = &lines;
    println!("{}", lines.len());
    let _ = worker;
    lines.push(format!("count={}", lines.len()));
    let clone = lines.clone();
    assert_eq!(clone, lines);

    let cell = RefCell::new(lines);
    let first = cell.borrow();
    let second = cell.borrow();
    println!("writer while read: {}", cell.try_borrow_mut().is_ok());
    drop(first);
    drop(second);
    let writer = cell.borrow_mut();
    println!("reader while write: {}", cell.try_borrow().is_ok());
    drop(writer);
    println!("writer after release: {}", cell.try_borrow_mut().is_ok());
}
Actual stdout · RefCell guard compatibility
1
1
writer while read: false
reader while write: false
writer after release: true
Actual stdout · synchronous pipeline
ERROR disk
worker: 1
scoped: 1
count: 1

Check the proof at the source boundary, then measure the implementation at the machine boundary. Neither view replaces the other.

End of Rust ownership · 8 levels, Idea to Machine

Where to next

Practical notes

  1. Note4 min read

    Fix “borrowed value does not live long enough” in Rust

    Keep the owner alive through the last borrow use, or return owned data. Five examples cover locals, borrowed structs, closures, temporaries and iterators.

Browse all 34 divesAll topics