In Rust, a pointer is a reference to a memory address, similar to the concept of pointers in languages like C/C++. However, Rust manages pointers safely, minimizing common problems like null pointers, dangling pointers, or unsafe concurrent access.
Rust offers different types of pointers to meet specific needs:
&
and &mut
)These are the most common types of "pointers" in Rust. A reference is a safe pointer that always points to valid memory and is managed by the borrow checker.
fn main() {
let x = 10;
let ref_x = &x; // An immutable reference to x's value
println!("Value of x: {}", x);
println!("Value via reference: {}", *ref_x); // Dereferencing
}
&T
) to the same value.&mut T
) at a time, and it cannot coexist with immutable references.fn main() {
let mut x = 10;
let ref_x = &mut x; // Mutable reference
*ref_x += 5; // Modifies the original value via dereferencing
println!("New value of x: {}", x);
}
*const T
and *mut T
)These are low-level pointers, similar to pointers in C. They allow direct manipulation of memory addresses but don't guarantee safety like references. Their use is rare and generally necessary only in specific cases (such as C interoperability or direct memory manipulation).
fn main() {
let x = 42;
let ptr_x: *const i32 = &x; // Immutable raw pointer
let mut y = 10;
let ptr_y: *mut i32 = &mut y; // Mutable raw pointer
unsafe {
println!("Value of x via raw pointer: {}", *ptr_x);
*ptr_y += 5;
println!("New value of y via raw pointer: {}", y);
}
}
Using raw pointers requires an unsafe
block because the compiler cannot verify if the code is safe.
Rust offers smart pointers, which are specialized types that encapsulate and manage references to values, ensuring safety and additional functionality.
Box<T>
): For dynamic allocation on the heap.Rc<T>
): Reference counter for sharing immutable data.Arc<T>
): Similar to Rc
, but thread-safe.Box
:fn main() {
let x = Box::new(10); // Allocates value 10 on the heap
println!("Value stored in Box: {}", *x);
}
Type | Main Use | Safety |
---|---|---|
&T , &mut T |
Immutable and mutable references | Safe and managed |
*const T , *mut T |
Direct memory manipulation | Unsafe (unsafe ) |
Box<T> |
Dynamic allocation (heap) | Safe and managed |
Rc<T> / Arc<T> |
Immutable data sharing | Safe and managed |
Rust prioritizes safety but provides tools to work directly with pointers when necessary, always with responsibility.