Rust Memory Safety
Rust's borrow checker is a strict but fair mentor. This skill codifies the patterns for working with it effectively.
The Trinity of Ownership
- Ownership: Each value has a single owner.
- Borrowing:
- Unlimited immutable borrows (
&T). - EXACTLY ONE mutable borrow (
&mut T) at a time.
- Unlimited immutable borrows (
- Lifetimes: Ensuring references are never valid longer than the data they point to.
Smart Pointers
Box<T>: Heap allocation for data with a known size at compile time.Rc<T>/Arc<T>: Reference counting for shared ownership (Arc is thread-safe).RefCell<T>: Interior mutability (checked at runtime).
Best Practices
- Prefer borrowing over cloning where possible.
- Use
Structlifetimes ('a) only when the struct doesn't own its data. - Avoid
unsafeunless performing FFI or low-level optimizations.