What Is Ownership in Rust and Why Does It Matter?

Ownership is Rust's compile-time system for managing memory by assigning a single owner to each value, ensuring safety without a garbage collector.

Ownership in Rust is a set of compile-time rules that determine which part of your code is responsible for managing memory for a specific value. It ensures memory safety without a garbage collector by enforcing that each value has exactly one owner, and when that owner goes out of scope, the memory is automatically freed. When you assign a value to a new variable, ownership is moved rather than copied, preventing double-free errors.

fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // Ownership of s1 is moved to s2
    // println!("{s1}"); // Error: s1 is no longer valid
    println!("{s2}"); // Valid: s2 owns the string
}