Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Operators and Expressions

The * dereference operator

Reference for the Rust * operator: dereferencing references, Box, Rc and raw pointers, the Deref and DerefMut traits, deref coercion and move-out errors.

The unary * operator follows a pointer to the value it points at. On a reference &T or &mut T it produces the T place; on a Box<T> it produces the boxed value; on any type that implements the Deref trait it calls deref() (or deref_mut() when a mutable place is needed). On a raw pointer, * is only allowed inside unsafe.

The result is a place expression, not a free-standing value: you can read it, assign to it (*r = 5) or borrow it again (&*r), but you can only move out of it if the type is Copy (or for Box, which is special). Most of the time you do not write * at all, because method calls, field accesses and function arguments auto-dereference.

Rust
let mut n = 5;
let r = &mut n;
*r += 1;
let b = Box::new(String::from("hi"));
let s: String = *b; // moves out of the box

Try it

Rust Dereferencing references and 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.

Rust Implementing Deref

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

For a type P that implements Deref<Target = T>:

Rust
pub trait Deref {
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}
pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;
}
Operand Result of *
&T, &mut T the place of type T
Box<T> the T inside; can be moved out
Rc<T>, Arc<T>, String, Vec<T>, Ref<T>, MutexGuard<T> T, str, [T], T, T, T, through Deref; no move out
*const T, *mut T T, only inside unsafe

Edge cases: *x in an immutable context calls *Deref::deref(&x); in a mutable context (assignment, &mut *x, method with &mut self) it calls *DerefMut::deref_mut(&mut x).

Usage notes

  • Cannot move out of a borrow: let s = *r; where r: &String is error E0507. Clone (r.clone()), take a reference (&*r, or just r), or use std::mem::take/replace.
  • Deref coercion: the compiler inserts &* automatically where a &U is expected and U: Deref, repeatedly if needed. This is why &String works as &str, &Vec<T> as &[T], and &Box<T> as &T.
  • Auto-deref in method calls and fields: r.len() and boxed.field dereference as many times as needed, so explicit * is mostly for assignment and for comparing or copying values.
  • Comparing references: == compares through references (&a == &b compares the values), but both sides need the same reference depth. * or ** aligns them.
  • Pattern alternative: |&x| and |&&x| in closures remove the reference in the parameter instead of using *x in the body.
  • Do not implement Deref for general inheritance. It is meant for smart pointers and thin wrappers. Using it to fake subclassing hides method sources and surprises readers.
  • Zero cost: dereferencing a plain reference is a pointer load. A user Deref is just a function call that normally inlines.
  • Raw pointers: reading *p requires unsafe and a valid, aligned, initialized target. See Unsafe Rust.