Ownership is Rust’s unique feature that ensures memory safety without garbage collection.
Ownership Rules
- Each value has a single owner
- Only one owner at a time
- When owner goes out of scope, value is dropped
let s = String::from("hello");
// s owns the string
Moving
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// s1 is no longer valid
Borrowing
fn calculate_length(s: &String) -> usize {
s.len()
}
let s = String::from("hello");
let len = calculate_length(&s); // Borrowing
Mutable References
fn change(s: &mut String) {
s.push_str(", world");
}
let mut s = String::from("hello");
change(&mut s);
Best Practices
- Use references when possible
- Understand ownership rules
- Avoid unnecessary moves
- Use
clone()sparingly - Leverage the borrow checker
Conclusion
Master Rust ownership for memory-safe systems programming! 🦀