struct - 在 Rust 中是否保证了 struct 字段的初始化顺序?

标签 struct rust initialization

我在 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


screenshot

关于struct - 在 Rust 中是否保证了 struct 字段的初始化顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61984925/

相关文章:

generics - 有没有一种方法可以实现与泛型相结合的 `as`语义?

java - 初始化静态类成员 - 请澄清一下

c - C 中未初始化局部变量的默认值

c - 将结构数组传递给 C 中不同文件中的函数

C# 结构 : Mutability versus Performance

rust - 是否可以使一种类型只能移动而不能复制?

c++ - 使用构造函数初始化对象数组

c - (C) 从文本文件读取结构

c - 在 C 上将数据保存为结构体的函数

Rust 表达式的空值