On this page
  1. Ownership, Borrowing, Lifetimes & RAII
  2. Contents
  3. The Three Ownership Rules & Move Semantics
  4. The Borrow Checker (&T vs. &mut T)
  5. Lifetimes ('a) & Elision Rules
  6. Deterministic Drop (RAII) Without a Garbage Collector

Ownership, Borrowing, Lifetimes & RAII

Prev: ownership_and_internals | Up: ownership_and_internals | Next: Traits, Generics & Dispatch
Rel: Memory Management Models, Call Stack & Heap, Drop, Copy
Ref: The Rust Book โ€” Understanding Ownership
Tags: #public #prog #rust #internals #ownership #memory


Contents


The Three Ownership Rules & Move Semantics

  1. Every value in Rust has a single owner variable.
  2. Assigning or passing a non-Copy value (String, Vec, File) moves ownership โ€” the previous binding is invalidated at compile time (preventing double-free).
  3. When the owner goes out of scope, the compiler automatically inserts a Drop::drop call (RAII).
let s1 = String::from("hello");
let s2 = s1; // Ownership moves to s2; using s1 afterwards is a compile-time error
println!("{s2}");

The Borrow Checker (&T vs. &mut T)

At any point in a scope, for a given value you may hold either:

This single compile-time aliasing XOR mutability invariant eliminates data races, iterator invalidation, and dangling pointers across both single-threaded and multi-threaded code.


Lifetimes ('a) & Elision Rules

Lifetimes ('a) are generic parameters telling the borrow checker how long a returned reference remains valid relative to input references. They are erased at compile time (zero runtime cost):

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

When there is one input reference (or &self), Rust's lifetime elision rules infer 'a automatically.


Deterministic Drop (RAII) Without a Garbage Collector

Local variables are dropped in reverse declaration order at scope exit (or early via std::mem::drop(val)), releasing heap buffers, closing File handles, and unlocking MutexGuards deterministically.

Linked from

Related notes