Puck
All tutorials
rust

Rust ownership in five minutes

How ownership, borrowing, and lifetimes keep memory safe without a GC.

Rust ownership in five minutes

Rust’s core idea is that every value has one owner. When the owner goes out of scope, the value is dropped.

Rules

  • Each value has a single owner at a time.
  • When the owner is moved, the previous binding can no longer use it.
  • You can borrow with &T (shared) or &mut T (exclusive).

Example

fn main() {
    let s = String::from("puck");
    let len = calculate_length(&s); // borrow, do not move
    println!("{s} has length {len}");
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

Ownership is why Rust can be fast and safe: no use-after-free, no double free, no data races in safe code.

Next

  • Try making a second mutable borrow and read the compiler error.
  • Explore clone when you truly need two owners.
Puck