Destructuring in Rust
Patterns pull structs, tuples and nested values apart in one binding.
struct Point {
x: i32,
y: i32,
}
struct Line {
from: Point,
to: Point,
}
fn main() {
let a = Point { x: 0, y: 0 };
let b = Point { x: 3, y: 4 };
let Line { from: Point { x, y }, to } = Line { from: a, to: b };
println!("from {x},{y} to {},{}", to.x, to.y);
let (first, .., last) = (1, 2, 3, 4);
println!("{first} {last}");
}
How it works
- Field shorthand binds a field to a variable of the same name.
- Nested patterns reach into a struct inside a struct.
..ignores the parts you did not name.
Keywords and builtins used here
LinePointabfni32letmainstruct
The run, in numbers
- Lines
- 19
- Characters to type
- 327
- Tokens
- 125
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 88 seconds.
Step 4 of 4 in Compound values, step 10 of 39 in Language basics.