Is Rust allowed to reorder fields of a tuple?

#[test]
fn test_00() {
    println!("{:?}", std::mem::size_of::<(u8, u16, u8)>())}

returned 4, which surprised me, implying that the two u8's were rearranged to be adjacent ?

Yes, all (effectively) #[repr(Rust)] layouts are unspecified and may be rearranged as the compiler pleases.

5 Likes

It's been that way since 1.18. Here's a blog post from the dev who implemented it: Optimizing Rust Struct Size: A 6-month Compiler Development Project | Blindly Coding

1 Like

FWIW, for those needing in-order tuples, using #[repr(C)] on a tuple struct works:

#[repr(C)]
struct Tuple<_0, _1 = (), _2 = (), _3 = (), _4 = (), _5 = ()> (
    _0, _1, _2, _3, _4, _5,
);

let padding = mem::align_of::<u16>() - mem::size_of::<u8>();
assert_eq!(
    mem::size_of::< Tuple<u8, u16, u8> >(),
    (1 + padding) + 2 + (1 + padding),
);
2 Likes

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.