Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order in which struct fields are initialized guaranteed in Rust?

I could not find any reference to this in Constructors - The Rustonomicon. Is it guaranteed that the following code…

struct Mutates {
    n: usize,
}

impl Mutates {
    fn side_effects(&mut self) -> usize {
        self.n += 1;
        self.n
    }
}

#[derive(Debug)]
struct Struct {
    a: usize,
    b: usize,
}

fn main() {
    let mut m = Mutates { n: 0 };

    // note the order of the fields
    dbg!(Struct {
        a: m.side_effects(),
        b: m.side_effects(),
    });
    dbg!(Struct {
        b: m.side_effects(),
        a: m.side_effects(),
    });
}

…will always print the following?

[src/main.rs:22] Struct{a: m.side_effects(), b: m.side_effects(),} = Struct {
    a: 1,
    b: 2,
}
[src/main.rs:26] Struct{b: m.side_effects(), a: m.side_effects(),} = Struct {
    a: 4,
    b: 3,
}

Or is it possible for the compiler to assign different values?

Note that the question is about the order in which fields are initialized, not declared.

Note that this question is specifically asking about structs and not tuples, which is answered by What is the evaluation order of tuples in Rust?.

like image 458
Lonami Avatar asked Feb 03 '23 15:02

Lonami


2 Answers

Yes, it's guaranteed. Ralf Jung, a compiler team contributor confirms it on Zulip:

Is the order in which struct fields are initialized guaranteed?

RalfJ:

yes -- it's always the order in which you write the fields in the initializer

the order of the fields in the struct definition is irrelevant

screenshot

like image 122
Heptametrical Avatar answered Feb 06 '23 15:02

Heptametrical


It's documented in The Rust Reference here that:

Expressions taking multiple operands are evaluated left to right as written in the source code.

This explicitly includes struct expressions. The documentation PR was https://github.com/rust-lang/reference/pull/888, which closed issue https://github.com/rust-lang/reference/issues/248 mentioned in Lonami's answer.

like image 33
Daira Hopwood Avatar answered Feb 06 '23 15:02

Daira Hopwood