How can I align a struct to a specified byte boundary?
huon's answer is good, but it's out of date.
As of Rust 1.25.0, you may now align a type to N
bytes using the attribute #[repr(align(N))]
. It is documented under the reference's Type Layout section. Note that the alignment must be a power of 2, you may not mix align
and packed
representations, and aligning a type may add extra padding to the type. Here's an example of how to use the feature:
#[repr(align(64))]
struct S(u8);
fn main() {
println!("size of S: {}", std::mem::size_of::<S>());
println!("align of S: {}", std::mem::align_of::<S>());
}
There's no way to specify alignment directly at the moment, but it is definitely desirable and useful. It is covered by issue #33626, and its RFC issue.
A current work-around to force alignment of some struct Foo
to be as large as the alignment of some type T
is to include a field of type [T; 0]
which has size zero and so won't otherwise affect the behaviour of the struct, e.g. struct Foo { data: A, more_data: B, _align: [T; 0] }
.
On nightly, this can be combined with SIMD types to get a specific high alignment, since they have alignment equal to their size (well, the next power of two), e.g.
#[repr(simd)]
struct SixteenBytes(u64, u64);
struct Foo {
data: A,
more_data: B,
_align: [SixteenBytes; 0]
}