Rust Dereferencing vs Destructuring — For the Kids 4/4

Cartoon of a boy opening a box labeled Dereferencing and a girl pulling a green block out of a box labeled Destructurung

This post is the fourth and last episode of a series of 4. If needed, start with episode 1. The list of episodes is at the end of the page.


TL;DR

  • Function and closure parameters are patterns too: we can destructure a tuple or a struct right in the signature.
  • In for loops, the loop variable is a pattern as well. Combined with .enumerate(), .iter(), or a filter, it destructures each item on the fly.
  • Destructuring moves unless the pieces are Copy or we borrow (&, ref).
  • Dereferencing accesses a value through indirection. Destructuring unpacks a value with a pattern. They often appear together, but they are two different operations.

Table of Contents


Where Are We?

In episodes 1 and 2 we covered dereferencing, through references and then through smart pointers. In episode 3 we started destructuring with let: tuples, arrays, structs, and enums. In this last episode we look at the other places where patterns show up, and we answer the three questions asked at the beginning of the series.


Destructuring: Function & Closure Parameters

fn destructuring05() {
    println!("\nDestructuring 05 : function & closure parameters\n");
    fn print_coordinates((x, y): (i32, i32)) {
        println!("Function received: x = {}, y = {}", x, y);
    }
    let point = (10, 20);
    print_coordinates(point);
    println!("{:?}", point);
    fn print_full_name((first, last): (String, String)) {
        println!("Function received: First = {}, Last = {}", first, last);
    }
    let chief = ("Martin".to_string(), "Brody".to_string());
    print_full_name(chief);
    // println!("{:?}", chief);// does not compile
    let points = vec![(1, 2), (3, 4), (5, 6)];
    points.iter().for_each(|&(x, y)| {
        println!("Point: x = {}, y = {}", x, y);
    });
    println!("Point: {:?}", points);
}

Expected output

Destructuring 05 : function & closure parameters
Function received: x = 10, y = 20
(10, 20)
Function received: First = Martin, Last = Brody
Point: x = 1, y = 2
Point: x = 3, y = 4
Point: x = 5, y = 6
Point: [(1, 2), (3, 4), (5, 6)]

Explanations

  • We define the function print_coordinates inside a function (destructuring05)
  • A point variable is defined and initialized (let point = (10, 20);)
  • Then it is used as an argument when we call print_coordinates (print_coordinates(point);)
  • The destructuring happens when the parameters are defined (fn print_coordinates((x, y): (i32, i32)) {...)
  • Since the data types of point are primitive (implement Copy trait), point is passed by value (it is copied)
  • point is still available after the call to print_coordinates and it can be printed

As we can expect, this is another story when the components are not primitive. To illustrate the point we:

  • Define a function print_full_name
  • chief is a tuple with 2 String. String do no implement Copy
  • We call print_full_name with chief as an argument
  • Since chief is based on non primitive data type, it is moved
  • The function parameter pattern (first, last): (String, String) performs destructuring directly in the function’s argument list.
  • It moves the two String values from the incoming tuple into the local variables first and last. These are new bindings with new stack addresses, although they may still point to the same heap-allocated buffers as the original values.
  • The commented-out println! does not compile since chief is gone (and the sharks are not guilty)

Destructuring: in for Loops with .enumerate()

Do you remember, not September (EWF, 1978), but destructuring04() and destructuring04_bis() where we passed the array by value then by reference. Here, we want to avoid the raw for loop (“no raw loops”, said Sean Parent in 2013). To do so we can use an iterator to visit an iterable (think of a vector, for example) from start to end.

fn destructuring06() {
    println!("\nDestructuring 06 : in for loops with .enumerate()\n");
    let characters = vec!["Hari", "Salvor", "Hober"];
    for (index, name) in characters.iter().enumerate() {
        println!("Character #{index} is {name}");
    }
    let characters = vec!["Harry".to_string(), "Hermione".to_string(), "Ron".to_string()];
    for (index, name) in characters.iter().enumerate() {
        println!("Character #{index} is {name}");
    }
}

Expected output

Character #0 is Hari
Character #1 is Salvor
Character #2 is Hober
Character #0 is Harry
Character #1 is Hermione
Character #2 is Ron

Explanations

The key point here is that in a for loop, the variable immediately after the for keyword is a pattern. That’s why we can destructure tuples directly inside the loop. Once we have this in mind, understanding the code is easier.

To keep in mind

The variable immediately after the for keyword is a pattern.

  • We create a vector of characters (&str) with let characters = vec!["Hari", "Salvor", "Hober"];
  • We iterate and enumerate over the vector (for (index, name) in characters.iter().enumerate(){...)
    • At each iteration
      • .iter() returns a reference to a &str (&&str)
      • .enumerate() wraps it into a tuple (usize, &&str)
    • Destructuring
      • index: binds to usize
      • name : binds to &&str
    • Printing
      • The compiler will apply implicit deref coercion
      • It will do something like *(&&str) = &str => A type which can be printed as usual.

Hum, hum… How can you be so sure about what you say ? “Trust in me, just in me…”. No, don’t trust people, check by yourself and here the debugger is your best friend. Below I put a breakpoint on the first println! and hover name. Do you see the data type in the yellow rectangle?

VS Code hover on name in a for loop over characters.iter().enumerate(): let name: &&str, framed in yellow

Under VSCode, with my setup, if I hit CTRL + ALT I can see the data type as overlays. Can you see the content of the red rectangle?

The same loop with inlay hints shown: name: &&str framed in red

This said, and always about the first for loop, if you have time play with the code below (Rust Playground is your second best friend after the debugger) :

fn destructuring06_bis() {
    println!("\nDestructuring 06 bis: in for loops with .enumerate()\n");
    let characters = vec!["Hari", "Salvor", "Hober"];
    for (index, name) in characters.iter().enumerate() {
        println!("Character #{index} is {name}");
        let bob = *name; // &str
        println!("{}", bob);
        // let bob = **name; // str, does not compile, no size known at compile-time
        // println!("{}", bob);
        // let bob = ***name; // ???, does not compile
        // println!("{}", bob);
        let bob = &name; // &&&str
        println!("{}", bob);
    }
}

It is time now to talk about the second for loop

let characters = vec!["Harry".to_string(), "Hermione".to_string(), "Ron".to_string()];
for (index, name) in characters.iter().enumerate() {
    println!("Character #{index} is {name}");
}
  • We create a vector characters of String with let characters = vec!["Harry".to_string()...
  • We iterate and enumerate over the vector (for (index, name) in characters.iter().enumerate(){...)
    • At each iteration
      • .iter() returns a reference to a String (&String)
      • .enumerate() wraps it into a tuple (usize, &String)
    • Destructuring
      • index: binds to usize
      • name : binds to &String
    • Printing
      • The compiler will apply implicit deref coercion
      • It will do something like *(&String) = String => A type which can be printed as usual.

In other words, we should have written the first line of the loop (*name), but, thanks to deref coercion we can write the second.

for (index, name) in characters.iter().enumerate() {
    println!("Character #{index} is {}", *name);
    println!("Character #{index} is {name}");
}

Destructuring: for Loop over Array Slices

fn destructuring07() {
    println!("\nDestructuring 07 : for loop over array slices\n");
    let coordinates = vec![[1, 2], [3, 4], [5, 6]];
    for &[x, y] in &coordinates {
        println!("x: {}, y: {}", x, y);
    }
    // Alternative: without destructuring
    for coord in &coordinates {
        println!("coord[0]: {}, coord[1]: {}", coord[0], coord[1]);
    }
}

Expected output

Destructuring 07 : for loop over array slices
x: 1, y: 2
x: 3, y: 4
x: 5, y: 6
coord[0]: 1, coord[1]: 2
coord[0]: 3, coord[1]: 4
coord[0]: 5, coord[1]: 6

Explanations

for &[x, y] in &coordinates may look like we’re referencing, but &[x, y] is a pattern. Indeed, it is placed after the for keyword. This said, let’s read the code :

  • we create a vector of 2-element arrays of i32 (let coordinates = vec![[1, 2]...)
  • coordinates is passed by reference to the for loop.
  • We are borrowing coordinates not consuming it
  • At each iteration, the for loop handles references to [i32, 2] (&[i32; 2])
  • &[x, y] is a destructuring pattern that matches a reference to a 2-element array
  • The compiler matches &[x, y] with each &[i32; 2]
  • Since i32 is primitive, it has the Copy trait, the values are copied into x and y (no ownership issues).
  • The second for loop shows how we can survive without destructuring

Destructuring: Destructuring Pattern in for Loop

This is the part that broke my brain when I first encountered it and what motivated me to write this post.

When iterating over a vector of strings by reference (&Vec<String>), I naively thought that writing for &s in &foundation{...} meant “give me the reference and then give me the value.” But that’s not what’s happening.

fn destructuring08() {
    println!("\nDereferencing 08 : destructuring pattern in for loop\n");
    let foundation: Vec<String> = vec!["Hari Seldon", "Salvor Hardin", "Hober Mallow", "The Mule"]
        .into_iter()
        .map(|s| s.to_string())
        .collect();
    // for &s in &foundation { // does not compile
    for s in &foundation {
        println!("String is : {}", s);
    }
}

Expected output

Dereferencing 08 : destructuring pattern in for loop
String is : Hari Seldon
String is : Salvor Hardin
String is : Hober Mallow
String is : The Mule

Explanations

  • Again, in Rust, the expression after for keyword is always a pattern — and here, &s is a destructuring pattern, not a reference.
  • We create a vector of String named foundation
  • foundation is passed by reference to the for loop
  • We are borrowing foundation not consuming it
  • Each element iterated is a &String, not a String
  • The commented-out for loop (for &s in &foundation {...) does not compile and here is why :
    • It tries to match a &String with the destructuring pattern &s
    • This would only work if s would be of type String
    • String type does not implement the Copy trait and and implicit cloning is not allowed
    • So it does not complie
  • The working for (for s in &foundation {)
    • It matches &String with the destructuring pattern s
    • This can work because a reference (an address) is a primitve type which can be copied
    • s is of type &String
    • Without deref coercion we should have to write println!("String is : {}", *s); (or .as_str())
    • Rust allow us to write println!("String is : {}", s);

To keep in mind

In a for loop, if we write &s, we are telling the compiler: “I want to destructure a reference and bind the value inside it.” It’s not the same as taking a reference.

To keep in mind

This may not be the canonical way of doing but… Here is how I design the destructuring pattern. I read the for loop backward

  1. What is the type of the iterated element (ex: String)
  2. Is it primitive or not (Copy or not, ex: No)
  3. Do I get a reference to it or not (ex: Yes)
  4. Design (ex: s, s is &String)

Destructuring: Filter and Destructuring Pattern in for Loop

Patterns can be used in loops to filter and destructure in a single step, let’s see how.

fn destructuring09() {
    println!("\nDestructuring 09 : filter and destructuring pattern in a for loop\n");
    let maybe_scores = vec![Some(10), None, Some(30)];
    // The pattern is a reference to an Option, so we match &Some(x)
    for &opt in &maybe_scores {
        match opt {
            Some(score) => println!("Score: {}", score),
            None => println!("No score"),
        }
    }
    // Alternative: filter out None before the loop
    for score in maybe_scores.iter().filter_map(|opt| opt.as_ref()) {
        println!("Got a score (filter_map): {}", score);
    }
    // Alternative : if-let inside the loop body
    for maybe in &maybe_scores {
        if let Some(score) = maybe {
            println!("Score via if-let: {}", score);
        }
    }
    // Alternative : flattening the Some directly in the iterator
    for score in maybe_scores.iter().flatten() {
        println!("Score via flatten: {}", score);
    }
}

Expected output

Destructuring 09 : filter and destructuring pattern in a for loop
Score: 10
No score
Score: 30
Got a score (filter_map): 10
Got a score (filter_map): 30
Score via if-let: 10
Score via if-let: 30
Score via flatten: 10
Score via flatten: 30

Explanations

  • We create may_scores a vector of Option<i32>
  • may_scores is passed by reference to the for loop
  • We are borrowing may_scores not consuming it
  • Each element iterated is a &Option<i32>, not a Option<i32>

First loop (for &opt in &maybe_scores {...)

  • It matches &Option<i32> with the destructuring pattern &opt
  • opt is an Option<i32>
  • It is used in the body of the for loop in a match expression
  • All variants of the options are listed

Second for loop (for score in maybe_scores.iter().filter_map(|opt| opt.as_ref()) {...)

  • This one is smart
  • maybe_scores.iter() creates an iterator on maybe_scores elements
  • .filter_map(|opt| opt.as_ref()) applies a filtering and transformation operation
    • opt is the output ot the previous iterator
    • filter_map takes a closure which must return Option<T>
      • For each element :
        • opt.as_ref() converts &Option<i32> to Option<&i32>
        • So here, if the element is Some(value), as_ref() returns Some(&value) otherwise it returns None
        • filter_map keeps only values where closure returns Some, and extracts the internal value
    • The result of filter_map is an iterator on references to non-None values
  • Then the score are printed

Third loop (for maybe in &maybe_scores {...)

  • Use an if let in the loop body
  • maybe is &Option<i32>
  • With if let Some(score) = maybe score get the value of maybe if the latare is not None
  • The score is printed

Fourth loop (for score in maybe_scores.iter().flatten() {...)

  • .flatten() is use to remove 1 level of nesting on an iterator of iterators.
  • When called on an iterator of Option values, .flatten() automatically filters out all None variants and unwraps the Some variants.
  • Here this means we iterate over the actual score values that exist, completely skipping any None entries

Any tips and tricks to share ? Here are a few common traps and surprises you might encounter (I did)

Rust Gotchas: Destructuring Edition

1. Shadowing Without Realizing It

You might accidentally shadow variables, leading to confusion or bugs if the shadowed value was still needed later.

let x = 5;
let (x, y) = (10, 20); // This shadows the previous `x`

2. Destructuring by Move (Not Copy)

Destructuring consumes values unless they implement Copy. Be careful with types like String, Vec, or custom structs.

let s = String::from("hello");
let (s1,) = (s,); // s is moved, not copied
// println!("{}", s); // error: borrow of moved value

3. Patterns Are Not Always Exhaustive in Match Arms

Failing to match all variants can cause a compilation error — or worse, if using _ too liberally, you might silently ignore important cases.

enum MyEnum { A(i32), B(String), C }

let x = MyEnum::C;
match x {
    MyEnum::A(n) => println!("A({n})"),
    MyEnum::B(_) => println!("B"),
    // MyEnum::C not covered!
}

4. Borrowing in if let and while let Is Tricky

To keep ownership, use a reference:

let opt = Some(String::from("hello"));
if let Some(s) = opt {
    println!("{}", s);
}
// println!("{:?}", opt); // moved!
if let Some(ref s) = opt { ... }

5. Destructuring &T vs T

If you destructure a reference (&pair), your pattern must also use &. This often confuses newcomers.

let pair = (1, 2);
let &(a, b) = &pair; // Need `&` pattern to destructure a reference

6. Too Much Pattern Nesting Hurts Readability

Consider breaking the destructuring into multiple lines or using named variables earlier for clarity.

let ((a, ), (c, d)) = ((1, 2), (3, 4)); // 😵‍💫

7. Partial Matching Requires ref or ref mut

let tuple = (String::from("hello"), 42);
let (_, n) = tuple; // moves the String

Use ref to avoid moving:

let (ref s, n) = tuple;

Answers to the Questions from Episode 1

The question is whether we can now either find the answerS ourselves or, at the very least, understand what causes the problem and the reasoning of the solution.

Q1

fn main() {

    let r = &Some(5);

    // `if let Some(val) = r` works even if r is a reference to an Option
    // thanks to “pattern matching on references”.
    if let Some(val) = r {
        // val is a reference to the inner value (&5), since r is a reference to an Option
        println!("val = {val}");
    } else {
        println!("No value found");
    }
}

No explicit *r — yet the pattern matches. How?

  • r is of type &Option<i32>
    • The pattern Some(val) matches &Some(5) because Rust implicitly treats it as &Some(val). This is part of Rust’s pattern matching behavior on references.
  • val is a reference to the inner value (&5). The println! macro accepts references, and Rust applies deref coercion automatically when formatting, so val prints as 5.

Q2

Now look at this one-liner:

let Some(x) = &Some(42);

Is this dereferencing, destructuring, or both?

fn main() {
    // Create a reference to an Option containing the value 42
    let opt = Some(42);

    // Destructure the Option using a let statement with pattern matching
    // If the Option in not Some, the demo code panic
    let Some(x) = &opt else {
        // Handle the None case (this block is required)
        panic!("Expected Some, found None");
    };

    // x is a reference to the value inside the Option
    println!("The value is: {x}"); // The value is: 42
}
  • This is destructuring only. No dereferencing occurs.
  • We use pattern matching to destructure the value of &opt, which has type &Option<i32>.
  • The pattern Some(x) is matched against &opt, and Rust implicitly treats it as &Some(x).
  • As a result, x has type &i32 — a reference to the inner value.
  • The else block is required in Rust 2021+ edition if the pattern might not match.
  • If opt is None, the else block is executed and the program panics.

Q3

One last example. Can you explain what’s going on here?

fn main() {
    // Create a Box containing a tuple (i32, &str)
    let b = Box::new((42, "hello"));

    // Dereference the Box to extract the values from the tuple
    let (x, y) = *b;

    // Now x and y hold the copied values from the Box
    println!("x = {x}, y = {y}"); // x = 42, y = hello

    // let (x, y) = b; // Does not compile
}
  • let b = Box::new(...) allocates a tuple on the heap and returns a Box<(i32, &str)>.
  • *b dereferences the box to get the tuple (42, "hello"), which is then destructured.
  • The line let (x, y) = b; doesn’t compile because we cannot directly destructure a Box<T> like that
  • The compiler does not automatically dereference Box<T> during pattern matching in let bindings.
  • We must explicitly dereference it using *b or use pattern matching with Box (let Box((x, y)) = b;)

Dereferencing vs Destructuring in Rust — Key Takeaways

Aspect Dereferencing Destructuring
Syntax *x let (a, b) = x
Semantics Access pointed value Extract elements of a structure
Applicable to &T, Box<T>, etc. tuple, struct, enum, array, etc.
Requires traits? Yes: Deref No (structural pattern matching)
  • Dereferencing means accessing the value behind a reference (&T, &mut T, Box<T>, Rc<T>, etc.). It’s about indirection.
  • Destructuring means unpacking a composite value (tuple, array, struct, enum) using patterns. It’s about pattern matching.
  • Dereferencing happens via *, but is often implicit thanks to deref coercion.
  • Destructuring can:
    • Move or borrow data depending on the pattern.
    • Be used in let, match, if let, function parameters, closures, and loops.
  • Patterns can be enriched with:
    • .. to ignore parts,
    • ref/ref mut to borrow during destructuring,
    • lifetimes when using &str or references,
    • match guards, nested patterns, and slice patterns.
  • Rust applies automatic deref and matching adjustments in match, making things feel “magical” — but they are deterministic.

Conclusion

At first glance, dereferencing and destructuring can feel like two sides of the same coin — both seem to “dig into” a value. But their roles are distinct.

  • Dereferencing is about accessing through indirection: it gives us the data behind a reference or a smart pointer.
  • Destructuring is about unpacking data into parts using pattern matching — whether in let, match, or function parameters.

Where dereferencing is a runtime operation (or often optimized away), destructuring is a compile-time syntactic feature. And while dereferencing can happen implicitly through deref coercion, destructuring always requires that your patterns match the shape of the data — with the possibility to borrow, copy, or move components depending on the context.

Understanding the difference between the two provides a clearer mental model of ownership, borrowing and data flow in Rust - especially when faced with a “lunar” message from the compiler.

I hope you’ve had as much fun reading these posts as I’ve had writing them. From now on, you should have a clear head and be able to explain destructuring and dereferencing to a buddy (Feynman method). If not, wait 2 or 3 days. Don’t reread the article, but run the examples through Rust Playground. Then link this or that part.

Webliography

The Posts Of The Series

  • Episode 1: dereferencing references, mutability, references as arguments
  • Episode 2: dereferencing smart pointers, Box, Rc, RefCell
  • Episode 3: destructuring tuples, structs, and enums with let
  • Episode 4: destructuring in parameters and for loops, answers, and takeaways

Back to top

Published on: Dec 2 2026 at 11:00 AM | Last updated: Dec 2 2026 at 05:50 PM

Copyright © 1964-2026 - 40tude