Sub topic 8
Destructuring tuples, structs, and nested enums
This chapter assumes you can define enums with data-carrying variants, write a basic match, and know the difference between moving and borrowing a value. It covers how patterns take values apart: tuples, structs, and enums nested inside each other.
What destructuring means
Destructuring is writing a pattern that has the same shape as a value, so Rust can pull the value apart and bind its pieces to names. You have already done this with Some(n). The same idea works for any composite type, to any depth.
Patterns appear in match arms, let statements, if let, while let, for loops, and function parameters. The rules in this chapter apply to all of them.
Tuples
A tuple pattern lists one sub-pattern per element. Each sub-pattern can be a name, a literal, a wildcard, or another pattern.
fn main() {
let point = (3, -2);
let (x, y) = point;
println!("x={x}, y={y}");
match point {
(0, 0) => println!("origin"),
(x, 0) | (0, x) => println!("on an axis at {x}"),
(x, y) => println!("at ({x}, {y})"),
}
}The program prints x=3, y=-2 and then at (3, -2). In the second arm, both sides of the | must bind the same names with the same types. That is why x appears in both.
Matching on a tuple is a common way to branch on two values at once, for example match (a.cmp(&b), flag).
Structs
A struct pattern names fields. You can bind a field to a new name with field: name, test it with field: literal, or use the shorthand field to bind a variable with the same name. Add .. to ignore the remaining fields.
struct Point {
x: i32,
y: i32,
}
struct Segment {
start: Point,
end: Point,
label: String,
}
fn main() {
let p = Point { x: 0, y: 7 };
match p {
Point { x: 0, y } => println!("on the y axis at {y}"),
Point { x, y: 0 } => println!("on the x axis at {x}"),
Point { x, y } => println!("at ({x}, {y})"),
}
let seg = Segment {
start: Point { x: 0, y: 0 },
end: Point { x: 4, y: 3 },
label: String::from("diagonal"),
};
let Segment {
start: Point { x: x1, y: y1 },
end: Point { x: x2, y: y2 },
..
} = seg;
println!("({x1}, {y1}) to ({x2}, {y2})");
}The program prints on the y axis at 7 and then (0, 0) to (4, 3). The .. skips label, so the String is never moved out of seg. Without .., a struct pattern must mention every field, and the compiler reports the ones you forgot.
Nested enums
Patterns nest as deeply as the data does. Each level of the pattern checks one level of the value. Here a command enum contains another enum and an Option.
enum Color {
Rgb(u8, u8, u8),
Named(String),
}
enum Command {
Move { x: i32, y: i32 },
Paint(Color),
Label(Option<String>),
}
fn describe(cmd: &Command) -> String {
match cmd {
Command::Move { x: 0, y: 0 } => "stay put".to_string(),
Command::Move { x, y: 0 } => format!("move horizontally by {x}"),
Command::Move { x, y } => format!("move to ({x}, {y})"),
Command::Paint(Color::Rgb(255, 0, 0)) => "paint red".to_string(),
Command::Paint(Color::Rgb(r, g, b)) => format!("paint #{r:02x}{g:02x}{b:02x}"),
Command::Paint(Color::Named(name)) => format!("paint {name}"),
Command::Label(Some(text)) => format!("label {text}"),
Command::Label(None) => "clear label".to_string(),
}
}
fn main() {
let commands = [
Command::Move { x: 0, y: 0 },
Command::Move { x: 5, y: 0 },
Command::Move { x: 2, y: 3 },
Command::Paint(Color::Rgb(255, 0, 0)),
Command::Paint(Color::Rgb(0, 128, 255)),
Command::Paint(Color::Named(String::from("teal"))),
Command::Label(Some(String::from("start"))),
Command::Label(None),
];
for cmd in &commands {
println!("{}", describe(cmd));
}
}The output is:
stay put
move horizontally by 5
move to (2, 3)
paint red
paint #0080ff
paint teal
label start
clear labelHow the compiler walks a nested pattern
Arms are tried from top to bottom. Within one arm, the check goes outside in and stops at the first mismatch. The diagram shows this for the Paint(Color::Rgb(255, 0, 0)) arm.
Order matters. The specific arm Rgb(255, 0, 0) must come before the general Rgb(r, g, b). If you reverse them, the specific arm can never match. The compiler warns that it is unreachable.
The exhaustiveness check also works through nesting. Delete the Label(None) arm and the compiler reports Command::Label(None) as the uncovered case. It names the exact inner value, not just the outer variant.
Ignoring parts of a value
You rarely need every piece. Rust has three ways to skip parts.
| Syntax | Meaning | Example |
|---|---|---|
| `_` | Matches one value and does not bind it | `(first, _, third)` |
| `_name` | Binds the value, but suppresses the unused-variable warning | `Some(_unused)` |
| `..` | Matches all remaining fields or elements | `Point { x, .. }` |
_ and _name differ in ownership. _ does not bind, so it never moves the value. _name is a real binding and moves a non-Copy value just as name would.
The .. form works in tuples, tuple variants, and slices. It can appear only once per pattern, so (.., x, ..) is an error.
fn main() {
let (first, _, third) = ("a", "b", "c");
println!("{first} {third}");
let nums = [10, 20, 30, 40];
let [head, .., tail] = nums;
println!("{head} {tail}");
if let [a, b, rest @ ..] = &nums[..] {
println!("{a} {b} {rest:?}");
}
}This prints a c, then 10 40, then 10 20 [30, 40]. The last pattern uses rest @ .. to bind the leftover slice to a name. It is refutable, because a slice can be too short, so it needs if let instead of let.
Irrefutable and refutable patterns
A pattern is irrefutable if it matches every possible value of its type. (x, y) against a tuple and Point { x, y } against a Point are irrefutable. A pattern is refutable if some values fail to match. Some(n) against an Option<i32> is refutable.
A plain let and a function parameter accept only irrefutable patterns. match arms, if let, and while let accept refutable ones. A bare let Some(n) = opt; is a compile error. Use if let or let ... else instead.
You can destructure in function parameters, which is handy for tuples and references:
fn distance_from_origin(&(x, y): &(f64, f64)) -> f64 {
(x * x + y * y).sqrt()
}
fn main() {
let points = vec![(3.0, 4.0), (6.0, 8.0)];
for p in &points {
println!("{}", distance_from_origin(p));
}
}This prints 5 and then 10. The &(x, y) pattern in the parameter strips the reference and takes the tuple apart in one step.
Common mistakes
- Misspelled variant names become variables. If you write
Paint(Colour::Rgb(..))with a name that doesn't exist, you get an error. A bare identifier in a pattern, though, always creates a new binding. Inmatch n { limit => ... },limitmatches anything and shadows any constant of that name. UseSelf::CONSTANTor a path such asColor::Red, and read warnings about unreachable arms. - Partial moves. Destructuring a non-
Copyfield out of an owned struct moves that field. The struct is then only partly usable. You can still read the fields that were not moved, but you can't use the whole struct. - Matching through a
Box. A pattern cannot see through aBox<T>. Dereference first, as inmatch *boxed { ... }, or match on a reference to the inner value. - Type mismatch with references. Matching
&Commandwith patterns written asCommand::Move { x, y }works because of default binding modes. The bindings become references,&i32here. The binding-modes chapter covers this in detail.
Summary of the working model
A pattern is a template for a value. Literals must be equal, names capture the value, _ and .. ignore it, and nested patterns recurse. The first arm whose template fits is the one that runs, and the compiler checks that every possible value fits some arm.
Exercise
Given enum Event { Click { x: i32, y: i32 }, Key(char), Scroll(Option<i32>) }, write a match on &Event that returns a String. It should return "top-left click" for a click where both x and y are 0, "click at (x, y)" for any other click, "enter" for the key '\n', "key c" for other keys, "scroll by n" for Scroll(Some(n)), and "scroll" for Scroll(None). Which arm must come before which, and why?
Show answer
Use the arms Event::Click { x: 0, y: 0 }, Event::Click { x, y }, Event::Key('\n'), Event::Key(c), Event::Scroll(Some(n)), and Event::Scroll(None). Each specific arm must precede the general arm for the same variant. Click { x: 0, y: 0 } must come before Click { x, y }, and Key('\n') before Key(c). Otherwise the general arm catches every value first, and the specific arm is unreachable, which the compiler flags with a warning. All variants and both Option cases are covered, so the match is exhaustive.
Exercise
Why does let Some(n) = maybe_number; fail to compile, and what are two ways to fix it?
Show answer
let requires an irrefutable pattern, and Some(n) fails to match when the value is None. One fix is if let Some(n) = maybe_number { ... }, which runs the block only on a match. The other is let Some(n) = maybe_number else { return; };, which leaves the function (or otherwise diverges) when the pattern does not match, and keeps n in scope afterwards.