Rust Ownership Rules Simplified
·
Rust Programming
Today I finally internalized Rust’s ownership rules. Here’s the simplified mental model that made it click:
The Three Rules
- Each value has exactly one owner
- When the owner goes out of scope, the value is dropped
- You can have either ONE mutable reference OR any number of immutable references
The Borrow Checker is Your Friend
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 is moved, can't use it anymore
// This would fail:
// println!("{}", s1);
// But this works:
println!("{}", s2);
}
References vs Ownership
fn main() {
let s = String::from("hello");
// Borrowing with &
let len = calculate_length(&s);
// s is still valid here!
println!("Length of '{}' is {}", s, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
The key insight: borrowing is temporary access without taking ownership.