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?.