Rust Reference ยท Operators and Expressions
The & and &mut borrow operators
Reference for Rust borrow expressions: & shared references, &mut exclusive references, &raw const and &raw mut, the aliasing rules and common borrow errors.
The prefix operators & and &mut create references to a place without taking ownership of it. &x is a shared reference (&T): any number can exist at once, and none of them can be used to modify the value. &mut x is an exclusive reference (&mut T): while it is alive, nothing else may read or write the value through any other path.
These two rules, checked at compile time by the borrow checker, are what make Rust memory-safe without a garbage collector. A reference can never outlive its target, and a value cannot be changed while someone else is looking at it. References are plain pointers at run time, with no cost.
let mut score = 10; let r = &score; // shared let m = &mut score; // exclusive (the borrow of r must be finished) *m += 1;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
&expr // shared borrow: type &T &mut expr // exclusive borrow: type &mut T &raw const expr // raw pointer: type *const T (Rust 1.82) &raw mut expr // raw pointer: type *mut T (Rust 1.82)
| Part | Description |
|---|---|
expr |
A place expression (variable, field, element, dereference). &mut needs a mutable place. A value expression is first stored in a temporary. |
| Lifetime | Inferred. It runs from the borrow to the last use of the reference (non-lexical lifetimes), not to the end of the block. |
Returns: a reference (or, for &raw, a raw pointer) to the place.
Errors: E0499 (second &mut while one is live), E0502 (shared and exclusive at the same time), E0505 (moving a value while it is borrowed), E0596 (taking &mut of an immutable binding), E0597 (the target does not live long enough).
Usage notes
- Aliasing XOR mutability: at any moment a place has either any number of
&borrows, or exactly one&mut, never both. Reading through the owner counts as a shared use. - Non-lexical lifetimes: since Rust 2018 a borrow ends at its last use, which is why the first example can take
&mut listright after the shared references were used. - Two-phase borrows:
v.push(v.len())compiles because the&mut vfor the call is only "activated" after the argument is evaluated. - Reborrowing: passing a
&mut Tto a function usually reborrows it automatically, so you can use it again afterwards.&*rreborrows a shared view of an exclusive reference. - Temporaries:
let r = &make();extends the temporary's life to the end of the block. A temporary in the middle of an expression only lives until the end of the statement. &in patterns and types:&xin a pattern destructures a reference (|&n| n + 1), andref/ref mutbind by reference inside patterns. These are not borrow expressions. See ref.- Raw borrows:
&raw const/&raw mutcreate a pointer without creating an intermediate reference. They are meant for packed or uninitialized data where a reference would be undefined behavior. Creating the pointer is safe; dereferencing it is not. - Not the same as
&&:a && bis logical AND, but&&xis a double borrow. The parser splits the token when it expects an expression. - Cloning ends the problem: if a borrow gets in the way and the data is small,
.clone()is often the pragmatic fix. For shared mutation useRefCellorMutex.
Related
- * dereference
- ref and mut
- move
- Tutorial: Borrowing, Lifetimes, Non-lexical lifetimes