Destructuring
Destructuring pulls the pieces out of a value by describing its shape instead of reaching in field by field. You write a pattern that mirrors the value, and Rust binds a name to each part.
Detailed Explanation
The plain-English idea: instead of writing let x = p.x; let y = p.y;, you write let Point { x, y } = p; and get both names at once. The pattern on the left looks like the value on the right, with names where the data is.
Formally, a pattern is a description of a value's structure. Destructuring is the act of matching a value against such a pattern and binding its parts. Tuples, arrays, slices, structs, tuple structs, and enum variants can all be destructured.
Why does this exist? Because in Rust a great deal of data lives inside enum variants, and the only way to get at it is to name the variant and its payload in the same breath. Option and Result are enums, so every match on them destructures. Languages without sum types get by with getters and null checks; Rust makes the shape check and the extraction one operation, which is why the compiler can prove you handled every case.
Destructuring works anywhere a pattern is allowed, not only in match:
| Position | Example |
|---|---|
let | let (a, b) = pair; |
| Function parameter | fn dist(Point { x, y }: Point) -> f64 |
for loop | for (name, score) in &map |
if let / while let | if let Some(user) = lookup(id) |
| Closure argument | .map(|(k, v)| k) |
Two shorthands come up constantly. .. is a rest pattern: it stands for "the fields or elements I did not name". In a struct pattern, Point { x, .. } binds only x. In a slice pattern, [first, .., last] binds the two ends and ignores the middle. Separately, _ matches one thing and binds nothing, so let (a, _) = pair; drops the second element.
Now the part that surprises people, and it is an ownership rule rather than a syntax rule. Destructuring by value moves each non-Copy field out of the original. If an Order has a String customer field, let Order { id, customer } = order; copies id (integers are Copy) but moves customer, and order is now partially moved. You cannot use order or order.customer afterwards. This is not destructuring being special; it is the same move you would get from order.customer on its own.
The fix is to destructure a reference: let Order { id, customer } = ℴ. Thanks to match ergonomics, added in Rust 2018, the bindings automatically become references, so customer is a &String and nothing moves. The older way to say this was ref and ref mut inside the pattern, which you still see in code written before 2018 and in the rare case where you destructure a value but want one field borrowed.
What does it cost? Nothing at runtime. Destructuring compiles to the same field reads you would have written by hand, and slice patterns compile to a length check plus indexing. The cost is readability in one direction only: a deeply nested pattern with six bindings is harder to read than three named locals, so stop nesting when the shape stops being obvious.
Code Examples
struct Point { x: i32, y: i32 }
// Destructuring in the parameter list: the caller passes a Point,
// the body sees x and y directly.
fn quadrant(Point { x, y }: &Point) -> u8 {
match (x > &0, y > &0) {
(true, true) => 1,
(false, true) => 2,
(false, false) => 3,
(true, false) => 4,
}
}
fn main() {
let p = Point { x: 3, y: -4 };
let Point { x, y } = &p; // borrows; p is still usable after this
println!("{x} {y}"); // prints: 3 -4
println!("{}", quadrant(&p)); // prints: 4
let (count, label) = (2u32, "retries");
println!("{count} {label}"); // prints: 2 retries
}Slice patterns: match on length and position at the same time.
// Slice patterns: match on length and position at the same time.
fn summarise(scores: &[i32]) -> String {
match scores {
[] => "no scores".to_string(),
[only] => format!("one score: {only}"),
// `..` swallows everything between the first and last element.
[first, .., last] => format!("from {first} to {last}"),
}
}
fn main() {
println!("{}", summarise(&[])); // prints: no scores
println!("{}", summarise(&[7])); // prints: one score: 7
println!("{}", summarise(&[7, 8, 9])); // prints: from 7 to 9
}struct Order {
id: u32, // i32/u32 are Copy, so this field is copied out
customer: String, // String is not Copy, so this field is moved out
}
fn main() {
let order = Order { id: 1, customer: String::from("Ada") };
let Order { id, customer } = order; // `order` is now partially moved
println!("{id} {customer}"); // prints: 1 Ada
// println!("{}", order.customer);
// error[E0382]: borrow of moved value: `order.customer`
let other = Order { id: 2, customer: String::from("Grace") };
// Destructure a reference instead: bindings become &u32 and &String.
let Order { id, customer } = &other;
println!("{id} {customer}"); // prints: 2 Grace
println!("{}", other.id); // fine: nothing was moved out of `other`
}Common Gotchas
Destructuring by value moves non-`Copy` fields
after `let Order { customer, .. } = order;` the compiler reports `error[E0382]` on any later use of `order` or `order.customer`. Destructure `&order` (or `&mut order`) when you only want to read the fields.
A struct pattern must be exhaustive unless you write `..`
`let Point { x } = p;` fails with `error[E0027]: pattern does not mention field 'y'`. Add `..` on purpose, not by reflex, because it silently absorbs fields added to the struct later.
Bare names in a pattern always create new bindings
`match n { limit => ... }` does not compare `n` against an existing `limit`; it shadows it and matches everything. To compare against a constant, the name must be an actual `const` or you must use a match guard such as `x if x == limit`.
`ref` is mostly historical
since match ergonomics landed, matching on a reference produces reference bindings automatically, so `ref`/`ref mut` appear only in older code or when you need one field borrowed out of a value you are otherwise moving.