Assigning struct members to variables in a single statement

Hello world! RustLang rookie here, with a strong Java background.

I wish to find out if it's possible to get all the individual members of a struct through a simple assignment.

#[derive(Default, Debug)]
pub struct Rect {
    pub len: usize,
    pub width: usize,

fn main() {
    // I tried this:
    let (len, width) = Rect::default();

    println!("LENGTH: {}", len);
    println!("WIDTH: {}", width);

Error generated:
expected struct `Rect`, found tuple

Is there a way to automatically assign struct members to variables in a single statement. Or does this apply only to tuples?

1 Like

The syntax is:

let Rect { len, width } = Rect::default();

That was fast. For a moment, I thought you were a bot. Thank you.

This forum is simply very active. :slight_smile:


In case you want more details, the keyword is "destructure".

1 Like

Thanks so much

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.