Rust Tutorial: References and Borrowing
Borrow values with & references. Understand mutable borrows and the rules that prevent data races.
Borrow without moving
References let you use a value without taking ownership. The owner keeps the value; the borrower gets a guaranteed-valid pointer.
What you'll learn in this Rust references and borrowing tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Immutable reference — Pass `&value` to borrow without moving. The function uses a reference `&String`.
- Many immutable borrows — Any number of immutable references can coexist — they all promise not to mutate.
- Mutable reference — `&mut` borrows mutably — you can modify through the reference.
- One mutable borrow at a time — Only one mutable reference can exist at a time. This prevents data races.
- Cannot mix mutable and immutable — Active immutable borrows prevent mutable borrows — they promise the data will not change.
- Non-Lexical Lifetimes (NLL) — Borrows end at their last use, not at end of scope. This makes the rules more flexible.
- No dangling references — Rust guarantees references always point to valid data.
- Borrowing summary — The rules:
Rust References and Borrowing concepts covered
- Borrow without moving