Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let mut score = 10;
let r = &score;          // shared
let m = &mut score;      // exclusive (the borrow of r must be finished)
*m += 1;

Try it

Rust Shared and exclusive references

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.

Rust A borrow error on purpose

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

Rust
&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 list right after the shared references were used.
  • Two-phase borrows: v.push(v.len()) compiles because the &mut v for the call is only "activated" after the argument is evaluated.
  • Reborrowing: passing a &mut T to a function usually reborrows it automatically, so you can use it again afterwards. &*r reborrows 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: &x in a pattern destructures a reference (|&n| n + 1), and ref/ref mut bind by reference inside patterns. These are not borrow expressions. See ref.
  • Raw borrows: &raw const/&raw mut create 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 && b is logical AND, but &&x is 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 use RefCell or Mutex.