Borrowing (Rust)

Borrowing lets you access a value through a reference (&) without taking ownership of it. The borrow checker enforces that borrows never outlive the data and never alias mutably.

Rust

Instead of moving a value into a function (and losing it), you borrow it by passing a reference. The function gets temporary access; the caller keeps ownership. This is how Rust shares data cheaply and safely.

The borrowing rules are the heart of the borrow checker: at any time you may have either any number of immutable references (&T) OR exactly one mutable reference (&mut T), but never both at once. This single rule eliminates data races at compile time.

A common beginner error is trying to mutate through a shared reference, or holding a mutable borrow while also reading the value elsewhere. Restructure the code so the mutable borrow ends before the next access, often by introducing a smaller scope.

Syntax

fn use_it(x: &T) { ... }   // immutable borrow
fn change(x: &mut T) { ... } // mutable borrow

Examples

Rust

fn len(s: &String) -> usize { s.len() }

fn main() {
    let name = String::from("Rust");
    println!("{}", len(&name)); // borrow, name still owned
    println!("{}", name);
}

Output:

4
Rust

Learn it in a lesson

See also

Back to the Dictionary