xvrqt
xvrqt

Reputation: 143

Does struct field declaration order matter in Rust?

I know that in C the compiler is not allowed to reorder struct fields and that this is important to the memory layout and alignment of the struct.

I am a beginner in Rust, and since it seems that for the most part raw pointers are hidden (I know you can still use them) if rustc is allowed to reorder the fields from their declared order in a struct.

Upvotes: 14

Views: 4276

Answers (1)

KamilCuk
KamilCuk

Reputation: 142035

From the Rust Reference Struct Types:

The memory layout of a struct is undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with the repr attribute. In either case, fields may be given in any order in a corresponding struct expression; the resulting struct value will always have the same memory layout.

Upvotes: 20

Related Questions