Does anonimous type has the same layout as named repr(C)?

Do these 3 things always have the same layout?

#[repr(C)]
struct Tuple1(u32, u32);
fn as_tuple(&self) -> &(u32, u32);
fn as_array(&self) -> &[u32; 2];

Tuple1 and [u32; 2] do. It's not guaranteed for (u32, u32).

3 Likes

Thanks for the answer.

It's not guaranteed for (u32, u32)

Why? Any reading regarding particularly (u32, u32)?

Tuples are repr(Rust) -- that's why (u8, u16, u8) is only 4 bytes†, when it'd be 6 bytes if it were repr(C).

† Currently, at least. It's not guaranteed.

2 Likes

Once you give layout guarantees, you're stuck with them forever [1], so most default layouts (#[repr(Rust)]) are not guaranteed. Arrays and slices are an exception, and there are a couple others.

For tuples specifically, consider that reordering the fields can enable it to be smaller due to alignment and stride constraints.

The layout of homogenous tuples (all the same type) may someday be guaranteed, but it is not today.


  1. until Rust 2.0, which might never exist ↩︎

5 Likes

Interesting. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.