How to refer a struct member to initialize another member of same struct in default?

I have below code

struct Rectangle {
    length: i32,
    width: i32,
}

impl Default for Rectangle {
    fn default() -> Self {
        Rectangle {
            length: 10,
            width: length * 2,
        }
    }
}

Here I'm trying to initialize width as 2*length in default. but this is giving me below compilation error.

cannot find value length in this scope

what could be the possible solution here?

Can define it as a variable, then use it to define both fields:

impl Default for Rectangle {
    fn default() -> Self {
        let length = 10;
        Rectangle {
            length,
            width: length * 2, // this refers to the variable, not the field
        }
    }
}
1 Like

Thanks, this works.

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.