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.
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
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
For a type P that implements Deref<Target = T>:
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;wherer: &Stringis error E0507. Clone (r.clone()), take a reference (&*r, or justr), or usestd::mem::take/replace. - Deref coercion: the compiler inserts
&*automatically where a&Uis expected andU: Deref, repeatedly if needed. This is why&Stringworks as&str,&Vec<T>as&[T], and&Box<T>as&T. - Auto-deref in method calls and fields:
r.len()andboxed.fielddereference as many times as needed, so explicit*is mostly for assignment and for comparing or copying values. - Comparing references:
==compares through references (&a == &bcompares 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*xin the body. - Do not implement
Dereffor 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
Derefis just a function call that normally inlines. - Raw pointers: reading
*prequiresunsafeand a valid, aligned, initialized target. See Unsafe Rust.