Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 814
xvrqt Avatar asked Aug 03 '19 02:08

xvrqt


People also ask

Does order matter in struct?

The order of fields in a struct does matter - the compiler is not allowed to reorder fields, so the size of the struct may change as the result of adding some padding.

How do you define a struct in Rust?

To define a struct, we enter the keyword struct and name the entire struct. A struct's name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call fields.


1 Answers

From the rust reference struct.md:

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.

like image 191
KamilCuk Avatar answered Sep 28 '22 03:09

KamilCuk