The Three Rules of Ownership in Rust Explained

Rust's ownership rules state that every value has one owner, only one owner exists at a time, and the value is dropped when the owner goes out of scope.

Rust's three ownership rules are: each value has exactly one owner, there can only be one owner at a time, and when the owner goes out of scope, the value is dropped. These rules ensure memory safety without a garbage collector by enforcing strict compile-time checks on data usage.

fn main() {
    let s = String::from("hello"); // Rule 1: 's' is the owner
    let t = s; // Rule 2: 't' becomes the owner, 's' is invalid
    // println!("{}", s); // Error: 's' was moved
} // Rule 3: 't' goes out of scope and memory is freed