Compile-time assert that two structs have the same size

const _SIZE_CHECK: [u8; mem::size_of::<i64>()] = [0; mem::size_of::<u64>()];

Is there a slightly less hacky way of writing this (with any pair of types, not u64 and i64, of course)?

We probably need to back up and ask why you want to do this, because in general, layout is not guaranteed to match even when the sizes are the same.

Normally it’s because you’re trying to use mem::transmute, which has its own size check, but I don’t think you can use that with generic types of your own.

I have a #[repr(u64)] enum. I want to convert between Box<[u64; 1000]> and Box<[MyEnum; 1000]> (one way can error, the other way can’t). I don’t know what layout has to do with this, but I want to make sure that if I ever change the u64 to u32 or something, I remember to change this code, too.

Well you said “with any pair of types” – layout is unspecified for non-repr(C) structs and enums with fields.

If you’re ok with unsafe, you could use a throwaway mem::transmute, in your conversion function, something like: let _: u64 = unsafe { mem::transmute(MyEnum::Foo) }; But I think your array _SIZE_CHECK is fine too.

1 Like