liveBook · Manning

Dereferencing

As explained in Rust in Action: Systems programming concepts and techniques

Dereferencing is the operation of accessing the value designated by a pointer or reference.

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

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains address-based references and unary syntax, then demonstrates NULL-pointer and segmentation-fault failures.
Examples
Uses a large-array reference, an integer-array search, raw memory scans, and printed variable addresses.
What it assumes
Assumes enough Rust to read variables, arrays, loops, and operators; teaches references and dereferencing through examples.
What you can do after
Apply it via Rust syntax to read values through references and diagnose why invalid raw-pointer dereferences crash.
How it connects
Connects references, pointers, raw pointers, unsafe blocks, NULL pointers, and segmentation faults.

Also explained in

Compare how 3 books explain dereferencing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.