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?.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With