Deep Dive: Rust Ownership

Rust's ownership model is what makes it unique among systems languages. In this article we'll walk through the three rules, with examples.

The Three Rules

  1. Each value has a single owner.
  2. When the owner goes out of scope, the value is dropped.
  3. You can have either
    • one mutable reference, or
    • any number of immutable references
    — but never both at the same time.

A First Example

Consider this code:

fn main() {
    let s = String::from("hello");
    takes_ownership(s);
}

fn takes_ownership(s: String) {
    println!("{}", s);
}

Comparison Table

OperationStackHeapNotes
Copyimplicit (Copy)requires .clone()primitive types only on stack
Moveinvalidates sourcedefault for String, Vec
Borrowcheapcheapchecked at compile time

"Ownership is Rust's most unique feature." — The Rust Book

Leave a Comment