Nested Pattern Destructuring In Let
Pull fields straight out of structs and tuples with destructuring patterns, combining nested matches with .. rest patterns.
Code
struct Shipment {
id: u32,
legs: Vec<(String, u32)>,
}
// 参数位置直接用结构体模式解构(destructuring)
fn summarize(Shipment { id, legs }: &Shipment) -> String {
match legs.split_first() {
Some((first, rest)) if !rest.is_empty() => {
let (city, _) = first;
format!("shipment {id}: via {city} plus {} more legs", rest.len())
}
Some((first, _)) => {
let (city, _) = first;
format!("shipment {id}: single leg to {city}")
}
None => format!("shipment {id}: no legs"),
}
}
fn main() {
let a = Shipment { id: 7, legs: vec![("rot".into(), 10), ("ams".into(), 5)] };
let b = Shipment { id: 8, legs: vec![("ham".into(), 3)] };
let c = Shipment { id: 9, legs: vec![] };
for s in [&a, &b, &c] {
println!("{}", summarize(s));
}
// let 解构元组:其余用 .. 忽略
let (first, ..) = (1, 2, 3, 4);
println!("first of tuple: {first}");
}How the snippet works
Nested Pattern Destructuring In Let comes down to the functions summarize and main.
Repetition is confined to for s in [&a, &b, &c] — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Using it
Signature: fn summarize(Shipment { id, legs }: &Shipment) -> String
Output lines are prefixed (first of tuple:), making each step’s effect easy to spot.
The entry point wires summarize together — run it once and the whole demo flows.
Key statements
Some((first, rest)) if !rest.is_empty() => {
let (city, _) = first;
format!("shipment {id}: via {city} plus {} more legs", rest.len())
}
Some((first, _)) => {
let (city, _) = first;
format!("shipment {id}: single leg to {city}")
}
Interactive Tools for This Topic
FAQ
- What does Nested Pattern Destructuring In Let print when run?
- Running the file directly is enough — expect labeled output lines such as `first of tuple:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.