Pointers in Rust
Rust supports references, allowing you to pass references to values and records within your program.
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.
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.
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:
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.