How does ownership work in Rust

Rust ownership assigns a single owner to each value, moving data on assignment and cleaning it up automatically when the owner goes out of scope.

Ownership in Rust ensures each value has exactly one owner, and when that owner goes out of scope, the value is dropped. When you assign a value to a new variable, ownership moves (transfers) rather than copying, preventing double-free errors. Use references and borrowing to access data without taking ownership.

let s1 = String::from("hello");
let s2 = s1; // Ownership moves to s2; s1 is invalid
// println!("{}", s1); // Error: use of moved value
println!("{}", s2); // Works