Destructuring In Parameters And For Loops
Destructure structs and tuples directly in function parameters and for loop bindings so nested data unwraps into named locals right at the binding site.
Code
#[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }
#[derive(Clone, Copy)]
struct Segment { from: Point, to: Point }
// 参数位置直接解构结构体:进函数体时已经是具名局部
fn manhattan(Point { x, y }: Point) -> i32 {
x.abs() + y.abs()
}
// 嵌套模式 + 剩余 ..:只取需要的字段
fn delta(Segment { from: Point { x: x1, y: y1 }, to: Point { x: x2, .. } }: Segment) -> (i32, i32) {
(x2 - x1, y2 - y1)
}
fn main() {
let legs = [
Segment { from: Point { x: 0, y: 0 }, to: Point { x: 3, y: 4 } },
Segment { from: Point { x: 3, y: 4 }, to: Point { x: 6, y: 4 } },
];
// for 循环绑定同样接受模式
for Segment { from, to } in &legs {
let (dx, dy) = (to.x - from.x, to.y - from.y);
println!("delta ({dx}, {dy}) from ({}, {})", from.x, from.y);
}
let total: i32 = legs.iter().map(|leg| manhattan(leg.from)).sum();
println!("manhattan total: {total}");
let (dx, dy) = delta(legs[1]);
println!("last leg delta: ({dx}, {dy})");
}How the snippet works
Count the functions manhattan, delta and main as the entire surface area of Destructuring In Parameters And For Loops.
The file repeats itself only inside for Segment { from, to } in &legs.
Using it
The main signature reads fn manhattan(Point { x, y }: Point) -> i32
Output lines are prefixed (delta (, manhattan total:, last leg delta: (), making each step’s effect easy to spot.
The entry point wires delta and manhattan together — run it once and the whole demo flows.
Key statements
let total: i32 = legs.iter().map(|leg| manhattan(leg.from)).sum();
fn delta(Segment { from: Point { x: x1, y: y1 }, to: Point { x: x2, .. } }: Segment) -> (i32, i32) {
(x2 - x1, y2 - y1)
}
fn manhattan(Point { x, y }: Point) -> i32 {
x.abs() + y.abs()
}
Interactive Tools for This Topic
FAQ
- What does Destructuring In Parameters And For Loops print when run?
- Execute the whole file; each printed line is prefixed with a label like `delta (`, `manhattan total:`, `last leg delta: (`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.