Primitive

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:


1. References (& 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.

Examples:

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
}

Reference Rules:

  1. You can have multiple immutable references (&T) to the same value.
  2. You can have only one mutable reference (&mut T) at a time, and it cannot coexist with immutable references.
  3. A reference can never be null or invalid.
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);
}

2. Raw Pointers (*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).

Example:

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);
    }
}

Note:

Using raw pointers requires an unsafe block because the compiler cannot verify if the code is safe.


3. Smart Pointers

Rust offers smart pointers, which are specialized types that encapsulate and manage references to values, ensuring safety and additional functionality.

Main Types:

Example with Box:

fn main() {
    let x = Box::new(10); // Allocates value 10 on the heap
    println!("Value stored in Box: {}", *x);
}

Summary: Pointers in Rust

Summary: Pointers in Rust

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.