Rust Dereferencing vs Destructuring — For the Kids 4/4
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
forloops, 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
Copyor 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?
- Destructuring: Function & Closure Parameters
- Destructuring: in
forLoops with.enumerate() - Destructuring:
forLoop over Array Slices - Destructuring: Destructuring Pattern in
forLoop - Destructuring: Filter and Destructuring Pattern in
forLoop - Rust Gotchas: Destructuring Edition
- Answers to the Questions from Episode 1
- Dereferencing vs Destructuring in Rust — Key Takeaways
- Conclusion
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_coordinatesinside a function (destructuring05) - A
pointvariable 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
pointare primitive (implement Copy trait),pointis passed by value (it is copied) pointis still available after the call toprint_coordinatesand 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 chiefis a tuple with 2 String. String do no implement Copy- We call
print_full_namewithchiefas an argument - Since
chiefis 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
Stringvalues from the incoming tuple into the local variablesfirstandlast. 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 sincechiefis 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
forkeyword is a pattern.
- We create a vector of
characters(&str) withlet 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 tousizename: 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.
- At each iteration
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?
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?
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
charactersofStringwithlet 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 aString(&String).enumerate()wraps it into a tuple(usize, &String)
- Destructuring
index: binds tousizename: 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.
- At each iteration
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]...) coordinatesis passed by reference to theforloop.- We are borrowing
coordinatesnot consuming it - At each iteration, the
forloop 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
i32is primitive, it has the Copy trait, the values are copied intoxandy(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
forkeyword is always a pattern — and here,&sis a destructuring pattern, not a reference. - We create a vector of
Stringnamedfoundation foundationis passed by reference to theforloop- We are borrowing
foundationnot consuming it - Each element iterated is a
&String, not aString - The commented-out
forloop (for &s in &foundation {...) does not compile and here is why :- It tries to match a
&Stringwith the destructuring pattern&s - This would only work if
swould be of typeString - String type does not implement the Copy trait and and implicit cloning is not allowed
- So it does not complie
- It tries to match a
- The working
for(for s in &foundation {)- It matches
&Stringwith the destructuring patterns - This can work because a reference (an address) is a primitve type which can be copied
sis 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);
- It matches
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
- What is the type of the iterated element (ex:
String)- Is it primitive or not (Copy or not, ex: No)
- Do I get a reference to it or not (ex: Yes)
- Design (ex:
s,sis&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_scoresa vector ofOption<i32> may_scoresis passed by reference to theforloop- We are borrowing
may_scoresnot consuming it - Each element iterated is a
&Option<i32>, not aOption<i32>
First loop (for &opt in &maybe_scores {...)
- It matches
&Option<i32>with the destructuring pattern&opt optis anOption<i32>- It is used in the body of the
forloop in amatchexpression - 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 onmaybe_scoreselements.filter_map(|opt| opt.as_ref())applies a filtering and transformation operationoptis the output ot the previous iteratorfilter_maptakes a closure which must returnOption<T>- For each element :
opt.as_ref()converts&Option<i32>toOption<&i32>- So here, if the element is
Some(value),as_ref()returnsSome(&value)otherwise it returns None filter_mapkeeps only values where closure returnsSome, and extracts the internal value
- For each element :
- The result of
filter_mapis an iterator on references to non-None values
- Then the score are printed
Third loop (for maybe in &maybe_scores {...)
- Use an
if letin the loop body maybeis&Option<i32>- With
if let Some(score) = maybescore get the value ofmaybeif 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?
ris 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.
- The pattern
valis a reference to the inner value (&5). Theprintln!macro accepts references, and Rust applies deref coercion automatically when formatting, sovalprints as5.
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,
xhas type&i32— a reference to the inner value. - The
elseblock is required in Rust 2021+ edition if the pattern might not match. - If
optisNone, theelseblock 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 aBox<(i32, &str)>.*bdereferences 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 aBox<T>like that - The compiler does not automatically dereference
Box<T>during pattern matching inletbindings. - We must explicitly dereference it using
*bor use pattern matching withBox(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 mutto borrow during destructuring,- lifetimes when using
&stror 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
- Patterns and Matching in RPL
- Patterns in the Rust Reference
- let statement in the Rust Reference
- Destructuring in the Rust Reference
- You’re welcome to share comments or suggestions on GitHub to help improve this article.