Skip to main content

Borrowing and references

Moving ownership everywhere would be exhausting, so Rust lets you *borrow* instead. A `&T` is a shared reference — read-only, and you can have as many as you like at once. A `&mut T` is an exclusive reference — you can change the value, but only one may exist at a time.

That single rule (many readers or one writer, never both) is what makes data races impossible in safe Rust. The compiler proves it before the program runs; there is no runtime lock and no performance cost.

Borrowing is also why functions usually take `&str` rather than `String`: they only need to look at the text, not own it.

Two mutable borrows at once

fn main() {
    let mut list = vec![1, 2, 3];
    let first = &mut list;
    let second = &mut list;
    first.push(4);
    second.push(5);
}

error[E0499]: cannot borrow `list` as mutable more than once at a time

Finish using one mutable borrow before creating the next. Usually that means scoping the borrow tightly, or just calling `list.push(4)` directly instead of holding a reference.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust