Rust ownership system eliminates entire categories of bugs — use-after-free, double free, data races — at compile time.
Ownership Rules¶
- Each value has exactly one owner
- When the owner leaves scope, the value is freed
- Ownership moves during assignment
Move and Borrowing¶
fn main() { let s1 = String::from(“hello”); let s2 = s1; // s1 moved to s2, s1 no longer valid! // Borrowing — reference let s3 = String::from(“world”); let len = calculate_length(&s3); // Immutable borrow println!(“{s3} has length {len}”); // s3 still valid // Mutable borrow let mut s4 = String::from(“hello”); change(&mut s4); } fn calculate_length(s: &String) -> usize { s.len() } fn change(s: &mut String) { s.push_str(” world”); }
Borrowing Rules¶
- Any number of immutable references (&T)
- OR one mutable reference (&mut T)
- Never both simultaneously
- References must be valid (lifetimes)
Key Takeaway¶
Ownership = memory safety without GC. Move, borrow (&), mutable borrow (&mut). The compiler is your friend.