Rs
Module 2Borrowing & ReferencesLesson 5 of 922 min

Mutable Borrows (&mut T)

Exclusive write access — update positions and books safely.

One writer, no readers

rust
let mut x = 10;
let r = &mut x;
*r += 1;
// let r2 = &x; // not while r is live

Methods that mutate

rust
fn improve_bid(q: &mut Quote, by: f64) {
    q.bid += by;
}

Why exclusive mut?

Prevents iterator invalidation and data races at compile time — critical when many components touch a book.

Exercise

Mutate a position quantity and average price after a fill.

Challenge

Implement apply_sell for reducing a long (ignore short-open for now).

Tips
  • Only one &mut at a time
  • NLL (non-lexical lifetimes) end borrows when last used
  • Weighted average is a classic mut borrow exercise

Try it live

Mutable Borrows (&mut T)Rust 2021
Loading editor…
Output
Press Run to compile and execute.