Rust Dereferencing vs Destructuring — For the Kids 3/4
This post is the third 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
- A pattern matches the shape of a value. Destructuring uses a pattern to break the value apart and extract its pieces.
- Patterns are not limited to
match:letuses them all the time. - With
..and_we can destructure only part of a tuple, an array, or a struct. - Destructuring moves or borrows the pieces depending on their type and on the pattern (
Stringvs&str,ref,&).
Table of Contents
- Where Are We?
- Patterns and Destructuring Patterns in Rust
- Destructuring: A Smooth Start
- Destructuring: Partial and Range Destructuring
- Destructuring:
structofi32withlet - Destructuring:
structofStringwithlet - Destructuring:
structof&strwithlet - Destructuring:
structof&strwithlet - Destructuring:
enumwithlet - Destructuring:
enumwithlet
Where Are We?
Episode 1 started with three short code samples that mix references and patterns, and then focused on dereferencing regular references. Episode 2 did the same with smart pointers (Box, Rc, RefCell).
Patterns and Destructuring Patterns in Rust
What is Destructuring? Destructuring is the act of using a pattern to break a value apart and extract its inner pieces. As we will see, we are not just assigning a value, we are unpacking it. However before diving into destructuring, it’s important to understand what a pattern is.
In Rust, a pattern is a syntax that matches the shape of a value. You’ve probably already seen patterns in match statements, if let, or while let — but patterns are everywhere: in let bindings, function and closure parameters, and for loops.
OK… But what is a pattern?
A pattern tells the compiler: “I expect a value of a certain shape — and I want to extract pieces from it.” Ok, let’s not waste time and go and see some code.
Destructuring: A Smooth Start
Too often we, me first, associate the concept of destructuring to match but this is too restrictive. Let’s start with some let statements. Copy and paste the code below in the Rust Playground then hit CTRL + ENTER
fn destructuring01() {
println!("\nDestructuring 01 : 101\n");
let (x, y) = (1, 2); // (x, y) is a pattern
println!("{x}, {y}");
let (x, y) = (1, 3.14); // tuple => we can have different data type
println!("{x}, {y}");
let [a, b, c] = [10, 20, 30]; // [a, b, c] is a pattern
println!("{a}, {b}, {c}");
let x = 42; // `x` is a very simple pattern: it matches any value and binds it to the name `x`
println!("{x}");
let ((x1, y1), (x2, y2)) = ((1, 2), (3, 4)); // nested destructuring
println!("{x1}, {y1}, {x2}, {y2}");
}
fn main(){
destructuring01();
}
Expected output
Destructuring 01 : 101
1, 2
10, 20, 30
42
1, 2, 3, 4
Explanations
- As I said, destructuring is the act of using a pattern to break a value apart and extract its inner pieces. In this context, a pattern is a syntax that matches the shape of a value. I like to compare it to regular expressions. Does the sequence of digits look like a phone number? If yes, extract the relevant parts.
- The first
letstatement matches(x, y)to(1, 2). Once the shapes match, the value 1 is assigned toxand 2 toy. I told you. A smooth start.- I hope you know why
letis a statement and not an expression. If you’re not sure, you can start with this Computer Science Vocabulary page then this page.
- I hope you know why
- Let’s talk again about the first
letbut with other words. Just to make sure… When destructuring, the pattern, the left-hand side must match the shape of the value on the right hand side. In this case, a 2-element tuple is matched by a 2-element pattern.- We are not surprised with a line like
let x = 1;. We understand that the Rust compiler infer the data type ofx. This also happens here. After all, with or without destructuring, the statement is aletstatement.
- We are not surprised with a line like
- The second
letstatement is similar to the first one except thatxandyhave different data type. Nothing magic here. Tuples can hold values of different datatype. The more important question is: “Does the shape on the left-hand side match the shape on the right-hand side?” This must be checked first, because even if both sides are tuples, they might have different numbers of elements. Once the shape is validated, one could imagine that theletstatement is unfold as a set of 2 “regular”letstatements (let x=1;andlet y=2;) - The third
letis similar to the first one but since we are matching two arrays,a,bandcwill all have the same data type (the type of the element in the rhs array). Again one coud imagine that once the shape is checked, the let statement is unfold as a set of 3 lines similar to :let a:i32 = 10;. You get the idea. - The fourth might be surprising, but first, if the notion of binding is not crystal clear, you can read this post (US). Here, the pattern on the left (
x) is a simple binding — it matches any value and assigns it tox. - The last
letstatement shows nested destructuring, where like with Russian Dolls, match act at different levels. Again think at the regular expression where we can define sub-patterns (also called groups).
At this point I would like to decompose the “process” in 2 steps. Indeed, everything looks like :
- Matching : Check if the left-hand side has the same shape as the right-hand side (think regular expressions).
- Destructuring : If matching is successful, break down the value and assign the components accordingly — effectively unfolding the
letinto multiple individualletstatements.
So, the good news is: everything we already know about let statements applies here too. For instance, destructuring works with custom data types, references, dereferencing, and so on. This also means that some bindings will move, while others copy, and in some cases, the compiler may perform deref coercion behind the scene. That’s part of the fun…
Let’s keep all this in mind for the moment and let’s look at some of syntactic options that the destructuring brings with it.
Destructuring: Partial and Range Destructuring
As explained, destructuring can be seen as a 2 steps process : matching then unfolding. As a developer we can imagine that during the matching part, it is useful to enhance the syntax of the left-hand side so that it can describe the set of items with some wildcards. Think about what we can do when we want to list the files of the current directory : ls my_file.*, or ls my_?ile.* for example.
Run the code below :
fn destructuring02() {
println!("\nDestructuring 02 : partial and range destructuring\n");
let (mut x, ..) = (41, 2, 3); // ignore the rest
x += 1;
println!("x: {x}");
let (.., z) = (1, 2, 101); // ignore the rest
println!("z: {z}");
let age = 15;
match age {
1..=17 => println!("No way to access the dance floor."),
_ => println!("Welcome to Studio 54!"),
}
let x = Some(1984);
match x {
Some(y) if y > 1964 => println!("Your are young."),
Some(_) => println!("Your are old."),
None => println!("Nothing."),
}
let pair = ("Hari Seldon", 12050);
let (_, just_the_year) = pair;
println!("We only care about the year: {}", just_the_year);
let num = Some(10);
match num {
Some(n @ 1..=10) => println!("In the range [1;10]: {n}"),
_ => println!("Other"),
}
}
Expected output
Destructuring 02 : partial and range destructuring
x: 42
z: 101
No way to access the dance floor.
Your are young.
We only care about the year: 12050
In the range [1;10]: 10
Explanations
This post is not a reference so I just show few of the “facilities” available in the matching step. The reference is here.
let (mut x, ..) = (41, 2, 3);: shows that we can use amutand that it is possible to extract only the first elementlet (.., z) = (1, 2, 101);: shows we can extract only the last element- This is not shown but yes you can write
let (x, .., z) = (31, 32, 33, 34, 35);
- This is not shown but yes you can write
- The third example (
1..=17 => println!(...) : shows how the pattern can be tested against a range of values - The fourth example (
Some(y) if y > 1964 => println!(...) : shows how to add a pattern guard in amatch let (_, just_the_year) = pair;: shows how to extract the parts of interest- The last example (
Some(n @ 1..=10) => println!(...) : shows binding with subpattern (aka @ binding pattern). It brings filtering and binding at the same time.
To keep in mind
Destructuring is a 2 steps process (matching, unfolding) and in the matching step we have means to describe the components we want to extract (think at
ls *.rs)
Let’s stay on the subject of partial destructuring and study the code below, in which we want to extract a member from a tuple that is not of primitive data type (String for example)
fn destructuring02_bis() {
println!("\nDestructuring 02 bis : partial and range destructuring\n");
let data = (String::from("Obi-Wan"), 42);
// This would move the String out of the tuple, making it unusable afterward:
let (s, _) = data;
println!("s: {}", s);
// println!("data.0: {}", data.0); // does not compile
let mut data = (String::from("Obi-Wan"), 42); // re-create data
// Instead, we can use `ref` to borrow the String by reference
let (ref s_ref, _) = data;
println!("Using `ref`: {}", s_ref); // s_ref is a &String
println!("Original still usable: {}", data.0); // data.0 is still valid
// Now let's use `ref mut` to get a mutable reference to the String
let (ref mut s_mut_ref, _) = data;
s_mut_ref.push_str(" Kenobi");
println!("Using `ref mut`: {}", s_mut_ref); // Modified through &mut String
println!("Original mutated: {}", data.0); // Shows the mutation
}
Expected output
Destructuring 02 bis : partial and range destructuring
s: Obi-Wan
Using `ref`: Obi-Wan
Original still usable: Obi-Wan
Using `ref mut`: Obi-Wan Kenobi
Original mutated: Obi-Wan Kenobi
Explanations
datais a tuple consisting of aString(not primitive) and ani32(primitive)- We extract (
let (s, _) = data;) and print the string part of the data. - The issue is that since String cannot Copy it is moved and
datais no longer available - The commented-out
println!line does not compile
What can we do ?
- We must re-create
dataas a mutable tuple (let mut data = (String::from("Obi-Wan"), 42);) - Then we use
refin the pattern to create an immutable reference instead of moving the value
If we need to be able to modify the extracted sub component
- We use
ref mutwhich allows mutating the original value via a mutable reference.
Just to make sure we talked about it… ref (ref_mut) can be used in match expressions as well. See below :
fn destructuring02_ter() {
println!("\nDestructuring 02 ter : ref in match expression\n");
let val = Some(String::from("Kenobi"));
// Match using `ref` to borrow the inner String instead of moving it
match val {
Some(ref x) => {
// x is a &String (reference), so we can use it without consuming `val`
println!("Borrowed from Some: {}", x);
},
None => println!("Got nothing"),
}
// We can still use `val` here because we didn't move its content
match val {
Some(x) => println!("Moved from Some: {}", x),
None => println!("Still nothing"),
}
// println!("{:?}", val); // does not compile: `val` was moved
}
Expected output
Destructuring 02 ter : ref in match expression
Borrowed from Some: Kenobi
Moved from Some: Kenobi
Explanations
valis anOptionon a non primitive data type (aStringhere)- In the first
matchexpression- We write
Some(ref x)(rather thanSome(x)) because, as in the previous code snippet, we don’t want to move (and loose)val xis of type&Stringso we shouldprintln!*xbut thanks to deref coercion we can usex
- We write
- In the second
match expression- We can use
valbecause it was not moved - However, here, we consume
val(match val {...)
- We can use
- After this second match,
valis no longer accessible - The commented-out
println!does not compile
Hm… What is the difference between ref x and *x? Again let’s use some code :
fn main() {
let &x = &42; // &x is a pattern
println!("x = {}", x); // x = 42
let x = &42; // a reference
println!("x = {}", x); // x = 42
println!("*x = {}", *x); // x = 42
let ref x = 42; // a reference
println!("x = {}", x); // x = 42
println!("*x = {}", *x); // x = 42
}
let &x = &42;- Right:
&42is a reference to an integer (&i32) - Left:
&xis a pattern that says: “I expect a reference, and I want to extract its value” - The
&in the pattern means: “I want to deconstruct a reference”. - Rust compiler implicitly dereferences
&42(*(&42)) to extract 42, and assigns it tox.
- Right:
let x = &42;- Right :
&42is a reference to an integer (&i32) - Left :
xis a binding whose value is a reference to the value
- Right :
let ref x = 42;- Right: 42 is an
i32. - Left:
ref xmeans: “Instead of getting the value, I want a reference to the value”
- Right: 42 is an
The second and third lines are functionally equivalent but the context differs
&is an operator, used in expression, on the right hand side (rhs)refis keyword, used in patterns (let,match,if let…) to create a reference.- We cannot use
&in a pattern because it already have another meaning (“I expect a reference, and I want to extract its value”)
- We cannot use
Destructuring: struct of i32 with let
fn destructuring03() {
println!("\nDestructuring 03 : struct of i32 with let");
#[derive(Debug)]
struct Point4D {
x: i32,
y: i32,
z: i32,
t: i32,
}
let pt = Point4D { x: 1, y: 2, z: 3, t: 2054 };
let Point4D { x, t, .. } = pt; // copy
println!("x: {x} and time: {t}");
println!("{:?}", pt); // pt is available
}
Expected output
Destructuring 03 : struct of i32 with let
x: 1 and time: 2054
Point4D { x: 1, y: 2, z: 3, t: 2054 }
Explanations
This one is easy.
- We create a new type named
Point4D. This is astructwith 4 fields of typei32(struct Point4D {...).#[derive(Debug)]is mandatory if we want toprintln!("{:?}..." - Then we create and initialize a variable
ptof that type (let pt = Point4D { x: 1, y: 2, z: 3, t: 2054 };) - The line
let Point4D { x, t, .. } = pt;is aletstatement that uses pattern destructuring to extract the fieldsxandtfrom thePoint4Dstruct, while ignoring the other fields. - The pattern “wants” a variable of type
Point4Dthat it will break apart (let Point4D { x, t, .. } = pt;)- Note that no matter the order, we only extract
xandt - Since the components are primitive type (
i32),ptis copied before the components are extracted
- Note that no matter the order, we only extract
- At the end, the 2
println!show how to use the extracted components and demonstrate thatptremains available after theletstatement.
Destructuring: struct of String with let
fn destructuring03_bis() {
println!("\nDestructuring 03 bis : struct of String with let");
#[derive(Debug)]
struct Person {
last_name: String,
first_name: String,
}
let luke = Person {
last_name: "Skywalker".to_string(),
first_name: "Luke".to_string()
};
let Person {last_name, first_name } = luke; // move because String does'nt have Copy trait
println!("{}-{}", last_name, first_name);
// println!("{:?}", luke); // does not compile
}
Expected output
Destructuring 03 bis : struct of String with let
Skywalker-Luke
Explanations
This is the same code except that the struct is now a struct of non-primitive datatype (part of the String in on the stack but the “chars” (the buffer) are on the heap). They are not primitive datatype like i32 or &str…
- We create a new type named
Person. This is astructwith 2 fields of typeString. - Then we create and initialize a variable
lukeof that type (let luke = Person { ...) - The
letstatement (let Person {last_name, first_name } = luke;) uses pattern destructuring to extract the fields - The patterns “wants” a variable of type
Personthat it will break apart (let Person {last_name, first_name } = luke;)- Since the components are String
lukeis moved before the components are extracted
- Since the components are String
- The
println!show how to use the extracted components - The commented-out
println!does not compile becauselukehas been moved and is no longer available (RIP)
Destructuring: struct of &str with let
In order to avoid the move (and the lost of luke) we may decide to use string slice (&str). The first idea of code we may have does not compile
fn destructuring03_ter() {
println!("\nDestructuring 03 ter : struct of `&str` with let");
#[derive(Debug)]
struct Person<'t> {
last_name: &str,
first_name: &str,
}
let luke = Person {
last_name: "Skywalker",
first_name: "Luke"
};
let Person {last_name, first_name } = luke;
println!("{}-{}", last_name, first_name);
println!("{:?}", luke);
}
The compiler complains because it wants to get, from us, the confirmation that the string slices will live long enough (it says : “expected named lifetime parameter” on each of the struct Person fields)
Below is a version that compile :
fn destructuring03_ter() {
println!("\nDestructuring 03 ter : struct of `&str` with let");
#[derive(Debug)]
struct Person<'t> {
last_name: &'t str,
first_name: &'t str,
}
let luke = Person {
last_name: "Skywalker",
first_name: "Luke"
};
let Person {last_name, first_name } = luke; // copy of &str
println!("{}-{}", last_name, first_name);
println!("{:p} - {:p}", last_name, first_name);
println!("{:?}", luke); // does compile
println!("{:p} - {:p}", luke.last_name, luke.first_name);
}
Expected output
Destructuring 03 ter : struct of &str with let
Skywalker-Luke
Pointer { addr: 0x5bb07cc760d7, metadata: 9 } - Pointer { addr: 0x5bb07cc76057, metadata: 4 }
Person { last_name: "Skywalker", first_name: "Luke" }
Pointer { addr: 0x5bb07cc760d7, metadata: 9 } - Pointer { addr: 0x5bb07cc76057, metadata: 4 }
Explanations
Basically, it’s the same code as the one that used String. We use &str instead and we had to indicate the lifetime
- We create a new type named
Person. This is astructwith 2 fields of type&'t str(&str+ lifetime annotation) - Then we create and initialize a variable
lukeof that type (let luke = Person { ...) - The
letstatement (let Person {last_name, first_name } = luke;) uses pattern destructuring to extract the fields - In the
letstatement, the patterns “wants” a variable of typePersonthat it will break apart (let Person {last_name, first_name } = luke;)- Since the components are of type
&str,lukeis copied before the components are extracted
- Since the components are of type
- The first 2
println!show how to use extracted components and display their respective addresses - The last 2
println!demonstrate thatlukeis still available after theletstatement. They also display the addresses of the components so that we can check they are the same as the one already printed. - This confirm that when the copy took place only the addresses were copied, not the buffer (the “chars”).
Destructuring: struct of &str with let
Here is another implementation of the same code. It does exactly the same thing and is not faster/slower. Only the let statement syntax differs.
fn destructuring03_qua() {
println!("\nDestructuring 03 qua : struct of &str with let");
#[derive(Debug)]
struct Person<'t> {
last_name: &'t str,
first_name: &'t str,
}
let luke = Person {
last_name: "Skywalker",
first_name: "Luke"
};
let &Person {last_name, first_name} = &luke;
// The line above is similar to the 2 lines below
// let ref = &luke;
// let Person {last_name, first_name} = ref;
println!("{} - {}", last_name, first_name);
println!("{:p} - {:p}", last_name, first_name);
println!("{:?}", luke);
println!("{:p} - {:p}", luke.last_name, luke.first_name);
}
Expected output
Destructuring 03 qua : struct of &str with let
Skywalker - Luke
Pointer { addr: 0x56815ba0b0d7, metadata: 9 } - Pointer { addr: 0x56815ba0b057, metadata: 4 }
Person { last_name: "Skywalker", first_name: "Luke" }
Pointer { addr: 0x56815ba0b0d7, metadata: 9 } - Pointer { addr: 0x56815ba0b057, metadata: 4 }
Explanations
Code similar to the previous one except the let statement.
- The
letstatement (let &Person {last_name, first_name} = &luke;) uses pattern destructuring to extract the fields - In the
letstatement, the pattern “wants” a reference to a Person that it will dereference before to extract the parts - It does a
*(&luke)to get access toluke. Then the components are extracted - The 4
println!display exactly the same information and confirmationlukewas copied- Only the addresses were copied, NOT the buffer.
Destructuring: enum with let
fn destructuring04() {
println!("\nDestructuring 04 : enum with let\n");
enum Role {
Emperor,
Trader(String),
Scientist { name: String, field: String },
}
let characters = vec![
Role::Emperor,
Role::Trader("Hober Mallow".to_string()),
Role::Scientist {
name: "Hari Seldon".to_string(),
field: "Psychohistory".to_string(),
},
];
for role in characters { // role is Role, characters is consumed
match role {
Role::Emperor => println!("The Emperor rules... vaguely."),
Role::Trader(name) => println!("A trader named {name}"),
Role::Scientist { name, field } => {
println!("Scientist {name} specializes in {field}")
}
}
}
println!("{}, characters"); // does not compile
let Some(x) = Some(5) else { todo!() }; // Some is an enum
println!("x: {x}");
}
Expected output
Destructuring 04 : enum with let
The Emperor rules... vaguely.
A trader named Hober Mallow
Scientist Hari Seldon specializes in Psychohistory
x: 5
Explanations
The first part of the sample code shows how one could build and print a collection of characters using a for loop and a match expression.
- First we define
Roleas anenum(enum Role {...) which have three variants:- Emperor, a
unitvariant with no associated data, - Trader, a
tuplevariant containing a singleString, - Scientist, a
structvariant with two named fields: name (String) and field (String).
- Emperor, a
- Then we build a collection of characters in a vector (
let characters = vec![...)- The collection have 3 members
- Each element is defined and initialized
- Now comes the interesting part where we print the content of the collection using a
forloop and amatch- At each iteration the current role is matched with all the possible variants
- Depending the role, more or less information are printed
Important : We must realize that in the for loop, role is of type Role. Indeed, we pass characters to the for loop, so behind the scene, the for loop calls .into_iter() which consume the vector and return a Role.
At the very end, since Some is an enum, the one on the rhs is destructured and its inner value is use to initialize x.
Destructuring: enum with let
Since we may not want to consume the collection of characters, the easiest way of doing is to use a reference and to destructure it in the match expression.
fn destructuring04_bis() {
println!("\nDestructuring 04_bis : enum with let\n");
#[derive(Debug)]
enum Role {
Emperor,
Trader(String),
Scientist { name: String, field: String },
}
let characters = vec![
Role::Emperor,
Role::Trader("Hober Mallow".to_string()),
Role::Scientist {
name: "Hari Seldon".to_string(),
field: "Psychohistory".to_string(),
},
];
for role in &characters { // role is &Role, characters not consumed
match role {
Role::Emperor => println!("The Emperor rules... vaguely."),
Role::Trader(name) => println!("A trader named {name}"),
Role::Scientist { name, field } => {
println!("Scientist {name} specializes in {field}")
}
}
}
println!("{:?}", characters);
let Some(x) = Some(5) else { todo!() }; // Some is an enum
println!("x: {x}");
}
Expected output
Destructuring 04_bis : enum with let
The Emperor rules... vaguely.
A trader named Hober Mallow
Scientist Hari Seldon specializes in Psychohistory
[Emperor, Trader("Hober Mallow"), Scientist { name: "Hari Seldon", field: "Psychohistory" }]
x: 5
Explanations
- The key difference is the way we pass
charactersto theforloop. - By reference (
for role in &characters {...) - In the
matchexpression, this timeroleis of type&Role
Hep, hep, hep! Break! OK, but the rest of the code is the same. How can this work ? You are right. Strictly speaking we should write something like :
match role {
&Role::Emperor => ...
&Role::Trader(ref name) => ...
&Role::Scientist { ref name, ref field } => ...
}
Indeed, in the for loop role is of type &Role so the match can be done with values of type &Role.
However, behind the scene, Rust compiler will do an implicit dereferencing of the pattern (see this page).
In plain English :
- The compiler detects
&Roleon thematchside andRoleon the variant side - The compiler automatically does a
*(role). In terms of data type it is similar to do a*(&Role). Tadaa! Now, on the match side, the compiler have aRolein hands it can match withRolevalues on the variant side.
To keep in mind
In a
matchexpression, Rust automatically applies a series of*(references)as long as this allows the pattern on thematchside to match the values type on the variants side.
To keep in mind
Pass reference to
forloop (for val in &array {...)
So far we destructured with let. In episode 4 we will see that patterns are also at work in function and closure parameters and in for loops, and we will finally answer the three questions of episode 1.