What is Ownership and Why Does It Exist?
What is Ownership and Why Does It Exist?
Ownership is Rust’s central memory management innovation. It governs how heap memory is allocated, accessed, and reclaimed without a garbage collector or manual free() calls.
The Three Rules of Ownership
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
fn main() {
{
let s = String::from("desk"); // s is valid from this point forward
println!("Inside scope: {}", s);
} // s goes out of scope; String memory is automatically freed here
}