Systems35 min · Lesson 1 of 4

Ownership & Borrowing

Understand the compiler rules that make Rust memory-safe without a garbage collector.

The Ownership Model

Unlike languages with a Garbage Collector (Java, Python) or manual memory management (C, C++), Rust introduces a third paradigm: Ownership. It guarantees memory safety at compile time.

Three Rules of Ownership

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.
fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // Ownership moves to s2
    
    // println!("{}, world!", s1); // ERROR: value borrowed here after move
    println!("{}, world!", s2); // Works perfectly
}

Borrowing with References

If we want a function to use a value without taking ownership, we pass a reference (&).

fn calculate_length(s: &String) -> usize { // s is a reference to a String
    s.len()
} // Here, s goes out of scope. But because it does not have ownership, nothing is dropped.

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);
    println!("The length of '{}' is {}.", s1, len);
}