Sub topic 8
Destructuring tuples, structs, and nested enums
This chapter assumes you know basic Rust syntax, structs and tuples, the match expression, and enums whose variants carry data. Destructuring means writing a pattern that mirrors the shape of a value, so Rust pulls the parts out into new variables in one step.
Destructuring tuples and structs
A tuple pattern lists one sub-pattern per element. A struct pattern names fields, and you can rename a field with field: name. Use .. to ignore the fields you don't need.
struct Point {
x: i32,
y: i32,
z: i32,
}
fn main() {
let pair = (3, -3);
let (a, b) = pair;
println!("{a} {b}");
let p = Point { x: 1, y: 2, z: 3 };
let Point { x, y: height, .. } = p;
println!("{x} {height}");
match pair {
(0, _) => println!("first is zero"),
(n, m) if n + m == 0 => println!("they cancel out"),
_ => println!("something else"),
}
}The same patterns work in let, function parameters, for loops, and match arms.
Destructuring enum variants
A pattern for a variant uses the variant's own syntax. Tuple variants use parentheses and struct-like variants use braces.
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
fn describe(shape: &Shape) -> String {
match shape {
Shape::Circle { radius } => format!("circle of radius {radius}"),
Shape::Rectangle { width, height } => format!("{width} by {height}"),
Shape::Triangle(a, _, _) => format!("triangle with first side {a}"),
}
}
fn main() {
println!("{}", describe(&Shape::Circle { radius: 1.5 }));
println!("{}", describe(&Shape::Triangle(3.0, 4.0, 5.0)));
}Because shape is a reference, the bound names (radius, a) are references to the fields. The binding modes chapter covers why.
Nesting patterns
Patterns nest to any depth. This lets you test an outer enum and an inner value in a single arm, without a second match.
enum Color {
Rgb(u8, u8, u8),
Named(String),
}
enum Command {
Paint { at: (i32, i32), color: Color },
Move(i32, i32),
Stop,
}
fn run(cmd: &Command) {
match cmd {
Command::Paint { at: (0, 0), .. } => println!("painting the origin"),
Command::Paint { at: (x, y), color: Color::Rgb(r, _, _) } => {
println!("paint ({x}, {y}) with red level {r}")
}
Command::Paint { color: Color::Named(name), .. } => {
println!("paint with {name}")
}
Command::Move(dx, 0) => println!("horizontal move by {dx}"),
Command::Move(dx, dy) => println!("move by {dx}, {dy}"),
Command::Stop => println!("stop"),
}
}
fn main() {
run(&Command::Paint { at: (0, 0), color: Color::Named("blue".to_string()) });
run(&Command::Paint { at: (2, 5), color: Color::Rgb(200, 10, 10) });
run(&Command::Move(4, 0));
run(&Command::Stop);
}Arms are checked from top to bottom. The (0, 0) arm must come before the general at: (x, y) arm, or it would never run.
Common errors
- Missing fields. A struct pattern must name every field or end with
... WritingPoint { x, y }for a three-field struct is a compile error. - Wrong shape.
Shape::Triangle(a, b)fails because the variant has three fields. Use_or..for the ones you ignore. - Unreachable arms. A broad arm placed first hides the narrower arms below it. The compiler warns about this.
- Refutable patterns in
let.let Command::Move(dx, dy) = cmd;fails becausecmdmight be another variant. Useif letorlet elseinstead.
Exercise
In the Command example, what does Command::Paint { at: (x, 0), .. } match, and which names does it bind?
Show answer
It matches any Paint command whose position has a y coordinate of 0, whatever its color. It binds only x. The .. ignores the color field, and the literal 0 binds nothing.
Exercise
Why does let Some(x) = maybe_value; not compile when maybe_value is an Option<i32>?
Show answer
The pattern is refutable, because maybe_value could be None, and a plain let requires a pattern that always matches. Use if let Some(x) = maybe_value, let Some(x) = maybe_value else { ... }, or a match that handles None.