Tracks
/
Rust
Rust
/
Syllabus
/
Destructuring
De

Destructuring in Rust

1 exercise

About Destructuring

Destructuring is the process of breaking down items into their component parts, binding each to smaller variables.

Destructuring Tuples

Destructuring tuples is simple: just assign new variable names to each field of the tuple:

let (first, second) = (1, 2);

Destructuring Tuple Structs

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

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");
}

Partial Destructuring

The .. operator can be used to ignore some fields when destructuring:

let ArabianNights { name, .. } = teller;
println!("{name} survived by her wits");

Conditional Destructuring

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:?}");
}
Edit via GitHub The link opens in a new window or tab