Understanding Ownership Rules
Ownership is Rust's core memory safety model, replacing garbage collection.
Key Ownership Rules
- Each value in Rust has a variable that's its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
Ownership Transfer
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // Error: s1 is no longer valid
This prevents double free errors.
Cloning
To deeply copy data:
let s1 = String::from("hello");
let s2 = s1.clone(); // s1 is still valid