Rules applied by Rust for reordering attributes

Hello!
I know that Rust can, if it want to, reorder attributes in a struct.
I know this can help if padding can be optimized out or limited but what is the rules applied by the compiler to do this?
Can I be sure that for example this structure is not reordered and can be considered to have the same memory layout has an slice of 4 float32 with x, y, z and w in the same order?

struct Vec4
{
    x: float32,
    y: float32,
    z: float32,
    w: float32,
}

Thank you,

1 Like

To avoid confusion - x, y, z and w are called fields in Rust, not attributes. Attributes are things like #[derive(Debug)].

To answer your actual question - Rust does not make any guarentees around data layout when using the default representation. Even if they are not reordered today, you can not rely on this, as it could change in a later compiler version.

If you need greater control over layout, you can to use the repr attribute to change the representation. For example, if you apply #[repr(C)] to a struct, it will apply the same layout rules as C.

4 Likes

Ok thank you, I was aware of the repr(C) attributes but I will be really surprise that Rust reorder struct without padding like Vec4, that will completely break possible SIMD generation.

If @17cupsofcoffee didn't give you enough to think about yet regarding Rust's data layout, you may also be interested in this awesome blog post.

But if you want your data to be layed out like an array in memory, maybe you should... just use an array?

type Vec4 = [f32; 4];
const X: usize = 0;
const Y: usize = 1;
const Z: usize = 2;
const W: usize = 3;

(The above is just the minimal implementation of the idea, realistic code will probably want to use a newtype of array in order to be able to add methods and such.)

1 Like

To be clear, I'm not saying that Rust will ever do this! The compiler developers just don't want to rule it out prematurely, as the language's stability guarentees would make it difficult for them to reverse that decision at a later date.

2 Likes

Thank you very much!

1 Like