Course contentsShow
← Rust
Lesson 22 of 1,9101. Rust Fundamentals and ToolingFree lesson

The Rules of Ownership

Apply the core principles of ownership to ensure memory safety without a garbage collector.

In this lesson, you will learn how Rust’s ownership rules act as the "traffic controller" for memory, ensuring your programs are safe without needing a garbage collector.

The Three Pillars

In most languages, the compiler or a runtime system manages memory for you. In Rust, we use a set of rules that the compiler checks at build time. To keep memory safe, Rust enforces these three fundamental laws:

  1. Each value in Rust has a variable that’s called its owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value is automatically dropped (cleaned up).

Putting Rules into Practice

Think of a variable as a "handle" to a piece of data. When you assign that data to a new variable, ownership moves. Consider this example:

fn main() {
    let s1 = String::from("Hello"); // s1 owns the data
    let s2 = s1; // Ownership moves to s2. s1 is now invalid!

    // println!("{}", s1); // This would cause a compile-time error
    println!("{}", s2);    // This works perfectly
}

In the code above, s1 is the original owner. When we assign s1 to s2, Rust doesn't copy the data (which could be expensive); it simply transfers the "keys" to the memory. Because s1 no longer owns the data, the compiler prevents you from using it. This avoids a dangerous bug called a "double free," where a program tries to delete the same memory address twice.

Automatic Cleanup

When the function reaches the closing curly brace }, the variable s2 goes "out of scope." Because s2 is the owner, Rust automatically calls a special function to free the memory. You don't have to manually malloc or free anything; the ownership rules guarantee that memory is reclaimed exactly when it is no longer needed.

By enforcing these strict rules, Rust eliminates common bugs like dangling pointers and memory leaks before your code even runs.

Key Takeaway: Ownership is a system of rules that ensures memory safety by tracking who owns a piece of data and automatically cleaning it up when the owner leaves the scope.