Dereferencing accesses the value designated by a pointer or reference. In Rust, & creates a reference and * dereferences one. A reference stores an address instead of duplicating potentially large data, so *r makes the referenced value available. section 2.6
The same operator works in ordinary references and raw-pointer operations, but the risks differ:
- A reference can provide inexpensive access to an existing value, such as adding a value to its referenced copy. section 2.6
- Iterating over &haystack makes each item a reference; *item retrieves the integer for comparison with needle. section 2.6
- Raw-pointer dereferencing reads memory directly and must occur inside an unsafe block; invalid addresses can cause a NULL-pointer failure or segmentation fault. section 6.4.2
Searching an array
for item in &haystack { if *item == needle { println!("{}", item); } } Each loop iteration gives item a reference to the next array element. Dereferencing it exposes the element's value for comparison. section 2.6
Listing 2.11 Searching for an integer in an array of integers
fn main() {
let needle = 0o204;
let haystack = [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147];
for item in &haystack { #1
if *item == needle { #2
println!("{}", item);
}
}
}
Inspect the complete array-search listing, including reference creation through iteration and dereferencing in the condition. section 2.6


