Pointers in Rust

Rust supports references, allowing you to pass references to values and records within your program.

fn main() {
    let mut i = 1;
    println!("initial: {}", i);

    zeroval(i);
    println!("zeroval: {}", i);

    zeroref(&mut i);
    println!("zeroref: {}", i);

    println!("reference: {:p}", &i);
}

We’ll show how references work in contrast to values with 2 functions: zeroval and zeroref. zeroval has an i32 parameter, so arguments will be passed to it by value. zeroval will get a copy of ival distinct from the one in the calling function.

fn zeroval(mut ival: i32) {
    ival = 0;
}

zeroref in contrast has a &mut i32 parameter, meaning that it takes a mutable reference to an i32. The *iref code in the function body then dereferences the reference to access the current value. Assigning a value to a dereferenced reference changes the value at the referenced address.

fn zeroref(iref: &mut i32) {
    *iref = 0;
}

The &mut i syntax gives a mutable reference to i.

References can be printed too, using the {:p} format specifier.

When we run this program, we’ll see:

$ cargo run
initial: 1
zeroval: 1
zeroref: 0
reference: 0x7ffee9c5e4ac

zeroval doesn’t change the i in main, but zeroref does because it has a reference to the memory location for that variable.

In Rust, references are similar to pointers in other languages, but with added safety guarantees. The Rust borrow checker ensures that references are valid and prevents common errors like dangling pointers or data races.