我在 Constructors - The Rustonomicon 中找不到任何对此的引用.是否保证下面的代码...
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(),
});
}
...将始终打印以下内容?
[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,
}
或者编译器是否可以分配不同的值?
请注意,问题是关于字段的顺序 初始化 ,未声明。
请注意,此问题专门询问 结构 而不是元组,这是由 What is the evaluation order of tuples in Rust? 回答的.
最佳答案
是的,这是有保证的。 Ralf Jung , compiler team contributor在 Zulip 上确认:
Is the order in which struct fields are initialized guaranteed?
拉尔夫:
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
关于struct - 在 Rust 中是否保证了 struct 字段的初始化顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61984925/