Destructuring
Destructuring unpacks structs, tuples, enums, and slices into bindings with patterns in let, match, and function parameters.
Busca en todas las páginas de la documentación
Destructuring unpacks structs, tuples, enums, and slices into bindings with patterns in let, match, and function parameters.
struct Point { x: i32, y: i32 }
fn main() {
let p = Point { x: 1, y: 2 };
let Point { x, y } = p;
println!("{x} {y}");
}When to reach for this: Extracting fields cleanly, matching nested data, and ignoring parts with ...
enum Shape {
Circle { radius: f64 },
Rect { w: f64, h: f64 },
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rect { w, h } => w * h,
}
}
fn main() {
let shapes = [Shape::Circle { radius: 2.0 }, Shape::Rect { w: 3.0, h: 4.0 }];
let total: f64 = shapes.iter().map(area).sum();
println!("{total}");
}What this demonstrates:
match&Shape avoid moving@ bindings: n @ 1..=10 captures whole value and subpatternlet Point { x, .. } = p; // ignore y and rest
let (_, second, ..) = tuple;match nested {
Outer::Inner(Point { x: 0, .. }) => {}
_ => {}
}ref / ref mut in PatternsBind by reference inside match to avoid moving fields.
let s = struct moves fields. Fix: match &val or ref patterns... in struct vs match - Update syntax ..other differs from pattern rest ... Fix: Context determines meaning.... Fix: Add .. for ignore rest.| Alternative | Use When | Don't Use When |
|---|---|---|
Field access p.x | One or two fields | Many fields or nested match |
| Accessor methods | Encapsulation | Simple data structs |
if let partial | Single variant | Many shapes |
| Records via macro | Boilerplate reduction | Standard derive enough |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026