rust-ownership-and-lifetimeslisted
Install: claude install-skill takurot/rust-skills-comprehensive
# Rust Ownership, Borrowing & Lifetimes
For "which idiom should I default to," see the general `rust-patterns` skill first. This
skill is for when a borrow/lifetime/ownership decision **is** the task: a compile error to
fix, a struct that needs to hold borrowed data, or a choice between `&T`, `Rc`, `RefCell`,
and cloning.
## Borrow checker error triage
Rust's borrow checker enforces two independent rules. Almost every borrow error is a
violation of one of them:
1. **Outlives rule**: a reference cannot outlive the value it borrows.
2. **Aliasing rule** ("aliasing XOR mutability"): for a given value, at any point in time,
you can have either (a) one or more shared `&T` references, or (b) exactly one exclusive
`&mut T` reference — never both.
| Compiler message / code | Which rule | Typical fix |
|---|---|---|
| `error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable` | Aliasing | End the shared borrow before creating the mutable one (see NLL below), or restructure so only one reference is live at a time. |
| `error[E0499]: cannot borrow `x` as mutable more than once` | Aliasing | You have two `&mut` at once — pass one by value/consume it, or scope them so they don't overlap. |
| `error[E0597]: `x` does not live long enough` / borrowed value dropped while still borrowed | Outlives | The referent is dropped before the reference is used. Extend the referent's lifetime (move it up a scope) or stop borrowing (clone, or restructure ownership).