3 ms·
> Rustc does not offer guarantees on the ordering of the fields. It's possible to guarantee the layout of a struct by opting into a specific representation, su
by kibwen 3y ago
> Rustc does not offer guarantees on the ordering of the fields.
It's possible to guarantee the layout of a struct by opting into a specific representation, such as the `repr(C)` shown in the OP.
- PartiallyTyped 3y agoThat's a special case and sits at the boundaries / bridge of languages. > There is no indirection for these types; all data is stored within the struct, as you would expect in C. However with the exception of arrays (which are densely packed and in-order), the layout of data is not specified by default. struct A { a: i32, b: u64, } struct B { a: i32, b: u64, } > Rust does guarantee that two instances of A have their data laid out in exactly the same way. However Rust does not currently guarantee that an instance of A has the same field ordering or padding as an instance of B. https://doc.rust-lang.org/nomicon/repr-rust.html https://doc.rust-lang.org/nomicon/repr-rust.html
- codeflo 3y agoIt’s not the default, but it’s just a language feature. It’s also not just for interfacing with C. For example, you also use repr(C) for pointer tricks even if you never leave Rust. Lots of places in the standard library use it for that reason.