Sub topic 3
Destructuring tuples into variables
This chapter assumes you know Rust let bindings, functions, and println!, and that you have seen tuple types and .0 field access. Here you will learn how to unpack a tuple into separate variables in a single statement.
What destructuring does
Destructuring is writing a pattern on the left side of let that has the same shape as the value on the right. Rust matches the shape and binds each part to a name.
fn main() {
let point: (i32, f64, &str) = (10, 2.5, "origin");
let (x, y, label) = point;
println!("{x} {y} {label}");
}Each name gets the value at the same position, and each variable keeps the type of its position. Here x is i32, y is f64, and label is &str. The pattern must have the same number of elements as the tuple. Writing let (x, y) = point; is a compile error because the tuple has three elements.
Ignoring parts you do not need
Use _ to skip one element. Use .. to skip all the elements you do not name.
fn main() {
let record = (7, "Ada", 36, true);
let (id, _, age, _) = record;
println!("{id} {age}");
let (first, ..) = record;
let (.., last) = record;
println!("{first} {last}");
}Only one .. is allowed in a pattern, because two would make the positions ambiguous.
Destructuring in other places
Patterns are not limited to let. You can destructure in function parameters, for loops, and match.
fn distance_from_origin((x, y): (f64, f64)) -> f64 {
(x * x + y * y).sqrt()
}
fn main() {
println!("{}", distance_from_origin((3.0, 4.0)));
let pairs = [(1, "one"), (2, "two"), (3, "three")];
for (number, name) in pairs {
println!("{number} is {name}");
}
match (3, -3) {
(0, 0) => println!("origin"),
(x, y) if x + y == 0 => println!("opposites"),
_ => println!("other"),
}
}The for loop is the most common use. Iterating over a collection of pairs and unpacking each one is clearer than writing pair.0 and pair.1.
Moving, copying, and borrowing
Destructuring a tuple that holds non-Copy values moves those values into the new variables.
fn main() {
let owned = (String::from("hello"), 42);
let (text, number) = owned;
println!("{text} {number}");
// `owned.0` was moved into `text`, so `owned` can no longer be used whole.
}To keep the original tuple, destructure a reference. Rust then binds each variable as a reference to the field.
fn main() {
let owned = (String::from("hello"), 42);
let (text, number) = &owned;
println!("{text} {number}");
println!("{}", owned.0);
}Here text is a &String and number is a &i32. This behavior is called default binding modes. It lets you write the same pattern for a reference as for the value.
Assigning to existing variables
A pattern can also appear on the left of = without let. This is called a destructuring assignment, and it is the idiomatic way to swap two values.
fn main() {
let mut a = 1;
let mut b = 2;
(a, b) = (b, a);
println!("{a} {b}");
}The right side is fully evaluated before either assignment happens, so the swap works without a temporary variable.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Mismatched types: expected a tuple with 3 elements, found one with 2 | The pattern has the wrong length | Add `_` or `..` to match the length |
| Borrow of moved value | A non-`Copy` field was moved out | Destructure `&tuple`, or clone the field |
| `..` used more than once | Two rest patterns in one tuple pattern | Use only one `..` |
Exercise
Given let data = (String::from("rust"), 3, 4.5);, write a let statement that binds only the i32 to count and leaves data fully usable afterward.
Show answer
let (_, count, _) = data; works because _ does not bind or move, and i32 is Copy. Afterward data can still be used in full. let (.., count, _) = data; would not compile, because it uses .. before the second element and leaves the pattern ambiguous.
Exercise
What do a and b hold after (a, b) = (b, a); when a is 1 and b is 2, and why does no temporary variable work?
Show answer
a is 2 and b is 1. Rust evaluates the whole right side, (2, 1), before it assigns to either variable.