Concept Flow - Destructuring patterns
Start with a value
Apply destructuring pattern
Extract parts into variables
Use extracted variables
End
Destructuring patterns break a value into parts and assign them to variables step-by-step.
let (x, y) = (10, 20); println!("x = {}, y = {}", x, y);
| Step | Action | Pattern | Value | Variables Assigned |
|---|---|---|---|---|
| 1 | Start with tuple value | (x, y) | (10, 20) | none |
| 2 | Match pattern to value | (x, y) | (10, 20) | x = 10, y = unassigned |
| 3 | Assign y from tuple | (x, y) | (10, 20) | x = 10, y = 20 |
| 4 | Use variables | N/A | N/A | Print x=10, y=20 |
| 5 | End | N/A | N/A | Variables x=10, y=20 in scope |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| x | unassigned | 10 | 10 | 10 |
| y | unassigned | unassigned | 20 | 20 |
Destructuring patterns let you split complex values into parts. Syntax: let (a, b) = (1, 2); Each pattern part matches a value part. All parts must match exactly. Variables get assigned in order. Use destructuring to simplify code.
(x, y) into variables a and b in Rust?let (a, b) = (x, y); correctly assigns a to x and b to y.let point = (3, 7);
let (x, y) = point;
println!("x = {}, y = {}", x, y);
point has values (3, 7). Destructuring assigns x = 3 and y = 7.println! macro outputs the values of x and y in order.let (a, b) = (1, 2, 3);
result?enum Shape {
Circle(f64),
Rectangle { width: f64, height: f64 },
}
let shape = Shape::Rectangle { width: 3.0, height: 4.0 };
let result = match shape {
Shape::Circle(radius) => radius * radius * 3.14,
Shape::Rectangle { width, height } => width * height,
};shape is a Rectangle with width 3.0 and height 4.0.Rectangle multiplies width and height: 3.0 * 4.0 = 12.0.Pass the test and this pattern moves unknown