Course contentsShow
← Rust
Lesson 84 of 1,9102. The Ownership ModelFree lesson

The Concept of Resource Ownership

Explain the single-owner principle that governs all memory transitions in Rust.

In this lesson, you will learn how Rust’s single-owner principle acts as the fundamental rule for memory safety.

The Single-Owner Principle

In many programming languages, memory management is left to a garbage collector or manual tracking. Rust takes a different approach: it enforces a strict rule where every piece of data has exactly one owner at any given time.

Think of it like a physical book. If you own the book, you can read it, lend it to someone, or—when you are finished—throw it away (deallocate the memory). If there were multiple owners, the system would become chaotic: who decides when to "throw the book away"? If one person burns it while another is still reading, you have a memory error.

In Rust, the owner is the variable that currently holds the value. When that variable goes out of scope, Rust automatically cleans up the resource.

How it works in code

Consider this simple example of resource transfer:

fn main() {
    let s1 = String::from("Hello"); // s1 is the owner
    let s2 = s1; // The ownership is moved from s1 to s2

    // println!("{}", s1); // This would cause a compile error!
    println!("{}", s2); // s2 is now the valid owner
}

When we assigned s1 to s2, the "resource" (the string data on the heap) was moved. s1 is no longer considered the owner. Because Rust knows s1 no longer owns that memory, it prevents you from using it. This design eliminates double-free errors and memory leaks, because the compiler knows exactly when the data is no longer needed: when the single owner goes out of scope.

This "move" semantics is the heart of Rust's safety. By ensuring there is only one "gatekeeper" for every resource, the compiler can guarantee that memory is freed exactly once, and only when it is safe to do so.

Key Takeaway: In Rust, every resource has exactly one owner, and transferring that ownership prevents the bugs typically caused by multiple parts of a program trying to manage the same memory.