Rust Ownership & Borrowing
Ownership rules, references, lifetimes, common patterns.
rustlanguage
# Rust Ownership & Borrowing
## Three rules
1. Each value has one owner.
2. When the owner goes out of scope, the value is dropped.
3. There can be many immutable references `&T` OR one mutable reference `&mut T`, never both at the same time.
## Move vs Copy
- Types without `Copy` (e.g. `String`, `Vec<T>`) are moved on assignment/argument.
- `Copy` types (e.g. `i32`, `bool`, fixed arrays of Copy) are duplicated.
## Borrowing
```rust
fn len(s: &String) -> usize { s.len() } // immutable borrow
fn push(s: &mut String) { s.push_str("!"); } // mutable borrow
let mut s = String::from("hi");
push(&mut s);
println!("{}", len(&s));
```
## Lifetimes
Tell the compiler how long references are valid.
```rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
```
## Common pitfalls & fixes
- "Cannot move out of borrowed content" -> use `.clone()` or take ownership.
- "Borrow checker conflict" in loops -> split logic, scope borrows, use indices.
- Need shared mutation -> `Rc<RefCell<T>>` (single-thread), `Arc<Mutex<T>>` (multi-thread).
## Smart pointers
- `Box<T>` heap allocation, owned
- `Rc<T>` shared ownership, single-thread
- `Arc<T>` shared, thread-safe
- `RefCell<T>` interior mutability, runtime borrow check
- `Cow<'a, T>` clone-on-write
## Slices
`&str` is `&[u8]` UTF-8 view. `&[T]` is a view into an array/Vec.
API: /api/skills/rust-ownership