Destructuring
In this page:
Destructuring a Tuple
A let statement can destructure a tuple directly into multiple named variables in one line, instead of accessing each element with .0, .1, and so on.
Example: Destructuring a Tuple
fn main() {
let point = (3, 7);
let (x, y) = point;
println!("x={}, y={}", x, y);
}
Login to try C/C++/Java/PHP code in the editor
Destructuring a Struct
Struct fields can be destructured into local variables of the same names directly in a let statement, using the struct's field names as the pattern.
Example: Destructuring a Struct
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 5, y: 9 };
let Point { x, y } = p;
println!("x={}, y={}", x, y);
}
Login to try C/C++/Java/PHP code in the editor
Ignoring Fields with ..
When you only need a few fields from a larger struct, .. in the pattern tells Rust to ignore all remaining fields without naming them individually.
Example: Ignoring Fields with ..
struct Config {
width: u32,
height: u32,
fullscreen: bool,
}
fn main() {
let cfg = Config { width: 1920, height: 1080, fullscreen: true };
let Config { width, .. } = cfg;
println!("Width: {}", width);
}
Login to try C/C++/Java/PHP code in the editor
Discarding Values with _
The underscore pattern _ matches any value while discarding it, useful in destructuring or function parameters when a value must be present but is not actually needed.
Example: Discarding Values with _
fn main() {
let (first, _, third) = (1, 2, 3);
println!("first={}, third={}", first, third);
}
Login to try C/C++/Java/PHP code in the editor
- Trying to destructure only some fields of a struct without using
..to explicitly ignore the rest, which is a compile error. - Forgetting the
_pattern can be used to intentionally discard a value you don't need during destructuring. - Assuming destructuring a reference automatically dereferences everything -- sometimes an explicit
&pattern or.clone()is needed.
- Destructuring extracts multiple named values from a tuple, struct, or enum in a single
letormatch. - The
..pattern can be used to ignore remaining fields you don't care about. - The
_pattern matches and discards any single value without binding it to a name. - Destructuring works in
letstatements, function parameters, and match arms alike.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: