Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Primitive Types

Rust references: &T and &mut T

Reference for Rust references: shared &T and exclusive &mut T, the aliasing rule, auto-dereferencing, reborrowing, comparing references and borrow errors.

A reference borrows a value without taking ownership. &T is a shared reference: any number may exist at once, and none can modify the value (apart from interior mutability). &mut T is an exclusive reference: while it lives, no other reference to the same value may be used. This "many readers or one writer" rule is checked at compile time and is the basis of Rust's memory safety.

References are never null and always point to valid data for their whole lifetime. They are plain addresses at run time (plus a length or vtable pointer for slices and trait objects), so borrowing costs nothing.

Rust
let mut n = 5;
let r = &n;        // shared
let m = &mut n;    // exclusive (after r is no longer used)

Try it

Rust Shared and exclusive borrows

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 Reborrowing and mutation through a reference

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
*r               // dereference
&'a T            // reference with a named lifetime
&raw const x     // raw pointer, not a reference
Form Description
&T Copy; any number at once; read-only unless T has interior mutability.
&mut T Not Copy; at most one usable at a time; allows reads and writes.
*r Reads or writes the pointee. Needed for assignment (*m = 4) and for arithmetic on primitive references.

Common errors: E0499 (two &mut at once), E0502 (a &mut while a & is alive), E0506 (assigning to a borrowed value), E0597 (the borrowed value does not live long enough), E0106 (missing lifetime specifier on a returned reference).

Usage notes

  • Auto-dereference: method calls and field access follow references as deep as needed, so rr.len() works through &&String. Operators do not: *a + *b is needed with &&i32, though &i32 + &i32 has its own impls.
  • Comparison looks at the pointee. &x == &y compares the values; std::ptr::eq compares addresses.
  • Reborrowing (&mut *r, done implicitly when you pass r to a function) lends the reference out for a short time and gives it back.
  • Non-lexical lifetimes: a borrow ends at its last use, not at the end of the block, so let a = &x; use(a); x += 1; compiles.
  • Lifetimes tie a returned reference to the inputs it came from; elision covers the common one-input case.
  • Niche: Option<&T> is the same size as &T, because the null address stands for None.
  • Coercions: &mut T converts to &T; &String to &str; &Vec<T> to &[T]; &Box<T> to &T (deref coercion).
  • Do not return references to locals. The compiler rejects it; return an owned value instead.