Sub topic 3
Destructuring tuples into variables
This chapter assumes you can already build a tuple, read a field with .0, and use let, match, and references in basic Rust. Here you will see how a pattern on the left side of let takes a tuple apart, and where else Rust accepts the same patterns.
The basic form
Destructuring puts a pattern where a variable name would normally go. The pattern has the same shape as the tuple, and each name in it binds one element.
fn main() {
let point: (i32, f64, &str) = (10, 2.5, "origin");
let (x, y, label) = point;
println!("{x} {y} {label}");
}x is an i32, y is an f64, and label is a &str. Each variable gets the type of the element at its position. Compare this with point.0, point.1, and point.2. Destructuring gives each value a name, so later code is easier to read.
flowchart LRThe diagram below shows how the pattern lines up with the value.
Skipping elements
A pattern must account for every element. There are two ways to skip some of them.
_ignores exactly one element and binds nothing...ignores any number of elements. You can use it only once in a pattern.
fn main() {
let record = ("Ada", 36, "London", true);
let (name, ..) = record;
let (.., active) = record;
let (_, age, _, _) = record;
println!("{name} {age} {active}");
}Use .. when the tuple is long. Use _ when position matters and you want that to be visible in the code. A name that starts with an underscore, such as _unused, still binds the value. Plain _ does not bind anything. That difference matters for ownership, as the next sections show.
Nested tuples
Patterns nest as deeply as the data does.
fn main() {
let line: ((i32, i32), (i32, i32)) = ((0, 0), (3, 4));
let ((x1, y1), (x2, y2)) = line;
let dx = (x2 - x1) as f64;
let dy = (y2 - y1) as f64;
println!("length = {}", dx.hypot(dy));
}The explicit type annotation on line is useful here. Without it, calling a method such as .pow(2) on an untyped integer fails with an "ambiguous numeric type" error.
Ownership: moves, copies, and borrows
Destructuring a tuple moves or copies its elements, using the same rules as any other assignment. A tuple of Copy types is itself Copy, so the original stays usable. Elements that own data, such as String, are moved.
Rust lets you move out of a tuple one field at a time. A _ pattern does not bind, so it does not move.
fn main() {
let pair = (String::from("key"), String::from("value"));
let (key, _) = pair;
println!("{key} {}", pair.1);
}pair.0 has moved into key, but pair.1 is untouched and still readable. If you wrote _value instead of _, the second string would move too, and the pair.1 access would fail to compile.
To avoid moving anything, destructure a reference. Rust then binds each name as a reference to the element (this is called default binding modes).
fn main() {
let pair = (String::from("key"), String::from("value"));
let (k, v) = &pair;
println!("{k} {v} {}", pair.0);
let mut counts = (0u32, 0u32);
let (hits, misses) = &mut counts;
*hits += 1;
*misses += 2;
println!("{counts:?}");
}Here k and v are &String. With &mut counts, hits and misses are &mut u32, so you assign through them with *. The mutable borrows end after their last use, so counts can be printed afterward.
Mutable bindings
Put mut on the individual name inside the pattern, not on the whole pattern.
fn main() {
let (mut total, step) = (0, 5);
for _ in 0..3 {
total += step;
}
println!("{total}");
}Only total is mutable. step is not.
Destructuring in assignments
Since Rust 1.59 you can destructure on the left of a plain assignment, with no let. The variables must already exist. This gives a compact swap and a clean Fibonacci step.
fn main() {
let (mut a, mut b) = (1, 2);
(a, b) = (b, a);
println!("{a} {b}");
let (mut prev, mut curr) = (0u64, 1u64);
for _ in 0..10 {
(prev, curr) = (curr, prev + curr);
}
println!("{curr}");
}The right side is evaluated completely before any assignment happens. That is why the swap works without a temporary variable.
Patterns outside `let`
The same tuple patterns work anywhere Rust accepts a pattern.
fn distance((x1, y1): (f64, f64), (x2, y2): (f64, f64)) -> f64 {
(x2 - x1).hypot(y2 - y1)
}
fn fizzbuzz(n: u32) -> String {
match (n % 3, n % 5) {
(0, 0) => "FizzBuzz".to_string(),
(0, _) => "Fizz".to_string(),
(_, 0) => "Buzz".to_string(),
_ => n.to_string(),
}
}
fn main() {
println!("{}", distance((0.0, 0.0), (3.0, 4.0)));
let names = ["ana", "bo"];
let scores = [90, 85];
for (i, (name, score)) in names.iter().zip(scores.iter()).enumerate() {
println!("{i}: {name} {score}");
}
let sums: Vec<i32> = [(1, 2), (3, 4)].iter().map(|&(a, b)| a + b).collect();
println!("{sums:?}");
println!("{}", fizzbuzz(15));
}- Function parameters can destructure their arguments, as in
distance. forloops usually destructure the tuples thatenumerateandzipproduce.- Closure parameters accept patterns.
|&(a, b)|strips the reference that.iter()adds. matchon a tuple of values tests several conditions at once, as infizzbuzz.
Refutable patterns
A pattern that always matches is irrefutable. (a, b) is irrefutable against a two-element tuple. A pattern such as (0, _) can fail, so it is refutable. Plain let accepts only irrefutable patterns. For refutable ones, use let ... else, if let, or match.
fn add_options(x: Option<i32>, y: Option<i32>) -> i32 {
let (Some(a), Some(b)) = (x, y) else {
return 0;
};
a + b
}
fn main() {
println!("{}", add_options(Some(2), Some(3)));
println!("{}", add_options(Some(2), None));
}Common errors
| Mistake | What the compiler reports |
|---|---|
| `let (a, b) = (1, 2, 3);` | Mismatched types: the pattern has 2 elements and the value has 3. |
| Using a variable after `let (s, _t) = pair;` moved a `String` | Borrow of partially moved value. |
| Two `..` in one pattern | The compiler rejects the pattern because `..` may appear only once. |
| `let (0, x) = pair;` | Refutable pattern in a local binding. Use `let ... else` or `match`. |
Exercise
What do a and b contain after this code runs, and why does it compile without a temporary variable?
let (mut a, mut b) = (3, 7);
(a, b) = (a + b, a - b);
Show answer
a is 10 and b is -4. The right side (a + b, a - b) is evaluated fully, using the old values 3 and 7, before either variable is assigned. Destructuring assignment then stores the two results into a and b.
Exercise
Given let pair = (String::from("x"), String::from("y"));, which of let (a, _) = pair; and let (a, _b) = pair; still allows println!("{}", pair.1) afterward?
Show answer
Only let (a, _) = pair;. A bare _ does not bind, so pair.1 is not moved. _b is a real binding, so it moves the second string and pair.1 can no longer be used.