tech

Rust Ownership Model

rustmemorysystems

Rust’s ownership model eliminates memory bugs at compile time without a garbage collector.

The Rules

  1. Each value has exactly one owner
  2. Ownership can be borrowed (&) or moved
  3. References must follow the borrowing rules

Example

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

The borrow checker feels restrictive at first. After a few weeks, you stop fighting it and start appreciating the safety guarantees.