Ownership & Memory

Ownership and memory notes explain how Rust decides who owns data, who may temporarily access it, and when cleanup runs. Start with Ownership, then connect moves, borrows, slices, copying, and destructors into one mental model.

Concepts

Patterns

Antipatterns

Learning path

Read The Stack and the Heap before Move Semantics if the pointer/heap distinction is still fuzzy. Read Borrowing, References, and Mutable References together; they are one rule set seen from three angles. Read The Slice Type before designing APIs that expose parts of strings or collections. Read Copy and Clone and The Drop Trait together to understand why resource owners move by default.

Example

fn main() {
    let owned = String::from("rust");
    let borrowed = owned.as_str();
 
    println!("{borrowed}");
 
    let moved = owned;
    println!("{moved}");
}

Best practice

  • ✅ Start from Ownership, then use Borrowing when a function only needs temporary access.
  • ✅ Reach for The Slice Type when returning or accepting views into contiguous data.
  • ✅ Treat Copy and Clone as explicit API design: cheap implicit copies are different from potentially expensive clones.
  • ✅ Let The Drop Trait and scope release resources instead of writing manual cleanup paths.

Pitfalls

See also

Ownership · Borrowing · References · Mutable References · The Slice Type · Move Semantics · Copy and Clone · The Drop Trait · The Stack and the Heap · Lifetimes

Sources