Pointer Types in Rust
Table of Contents
Box
- Used for explicitly allocating values on the heap.
- Provides exclusive ownership.
- Use
Box when you want to opt-in to storing something on the heap, which otherwise wouldn't go there.
- Generally, use
Box when:
- Writing a recursive type.
- Optimizing the code (e.g., a large
struct that is expensive to move around).
- Want to use
dyn SomeTrait and have ownership of it.
Arc and Rc:
- Both
Arc and Rc are reference counting types that provide shared ownership.
- Anything shared with
Arc or Rc is immutable.
Arc is more expensive, but is thread-safe.
Rc is less expensive, but is not thread-safe.
Cell, RefCell, and Mutex
- All three
Cell, RefCell, and Mutex provide shared ownership.
- Anything shared with
Cell, RefCell, or Mutex is mutable.
Cell and RefCell are not thread-safe.
Mutex is thread-safe.
- Use
Cell if the type is Copy, RefCell otherwise.
Cow
Cow is a clone-on-write smart pointer.
- Usually used with strings.
- Generally, use
Cow for optional ownership (i.e., operations that may or may not modify input).
Cow is also a smart pointer.
*const T and *mut T
- Both
*const T and *mut T represent a generic raw pointer.
- Dereferencing
*const T yields an immutable place expression, *mut T yields a mutable one.
- A place expression is an expression that represents a memory location.
- In terms of variance,
*const T is covariant, while *mut T is invariant.