Destructuring is the process of breaking down items into their component parts, binding each to smaller variables.
Destructuring tuples is simple: just assign new variable names to each field of the tuple:
let (first, second) = (1, 2);
Destructuring tuple structs is identical to destructuring tuples, but with the struct name added:
struct TupleStruct(&'static str, i32);
let my_tuple_struct = TupleStruct("foo", 123);
let TupleStruct(foo, num) = my_tuple_struct;
Destructuring structs is similar to destructuring tuple structs. Just use the field names:
struct ArabianNights {
name: String,
stories: usize,
}
let teller = ArabianNights { name: "Scheherazade".into(), stories: 1001 };
{
let ArabianNights { name, stories } = teller;
println!("{name} told {stories} stories");
}
The ..
operator can be used to ignore some fields when destructuring:
let ArabianNights { name, .. } = teller;
println!("{name} survived by her wits");
Destructuring structs and tuples is infallible. However, enums can also be destructured, using the if let
, while let
, and match
language constructs.
if let Some(foo) = foo {
println!("{foo:?}");
}