Ownership & Borrowing · 14 min · free with an account

Borrowing

Lesson preview · about 30%

Borrowing lets code use a value without taking ownership.

Core idea

Many shared borrows or one mutable borrow, never both at once.

Start with the idea

Rust permits many shared references or exactly one mutable reference, never both. The compiler tracks the region where each borrow is actually used, so a borrow ends at its last use rather than at the end of the block — which is why moving one line is often the whole fix.

Borrowing lets a function use data while its owner remains responsible for it. A shared reference, written &T, permits reading; many readers can coexist. A mutable reference, &mut T, permits writing but must have exclusive access for the duration of that borrow. This rule prevents a reader from holding a pointer into a vector while a writer grows the vector and possibly moves its buffer.

In the example, first points at the first element of items. The print is its last use. Only after that point does items.push(...) change the vector.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery