Topic
Borrowing
Borrowing lets you use a value without taking ownership. You pass a reference instead of the value itself, and the original stays valid. The borrow checker enforces two rules: only one mutable reference at a time, and references must always point to valid data.
Quick Reference
ConceptWhat it means
&TAn immutable reference — borrow a value for reading only
&mut TA mutable reference — borrow a value and be allowed to change it
Rule 1Either one mutable reference or any number of immutable ones, never both at the same time
Rule 2References must always be valid — no dangling pointers
Dangling referenceA reference to data that has already been dropped. Rust refuses to compile this.
Inner scope { }Wrapping a reference in a block drops it when the block ends, freeing the borrow
TermWhat it meansWhen you use it
Borrow &TA read-only reference — you can look but not changeWhen a function only needs to read a value
Mutable borrow &mut TA read-write reference — you can change the valueWhen a function needs to modify a value
Rule 1Either one mutable reference or any number of immutable ones, never bothEvery time you create a reference
Rule 2References must always be valid — no dangling pointersCompiler enforces this automatically
LifetimeHow long a reference stays valid — compiler tracks this automaticallyYou read lifetimes in Anchor; rarely write them yourself
Inner scopeWrapping a reference in { } drops it when the block endsWhen you need sequential mutable references