如何将结构与指定的字节边界对齐?

How can I align a struct to a specified byte boundary?

我需要将结构与 Rust 中的 16 字节边界对齐。似乎可以通过 repr attribute 给出有关对齐的提示,但它不支持这个确切的用例。

我要实现的功能测试是一种类型 Foo 这样

assert_eq!(mem::align_of::<Foo>(), 16);

或者,具有字段 baz 的结构 Bar 使得

println!("{:p}", Bar::new().baz);

总是打印一个能被 16 整除的数字。

目前这在 Rust 中可行吗?有任何解决方法吗?

目前无法直接指定对齐方式,但这绝对是可取且有用的。它被 issue #33626, and its RFC issue.

覆盖

强制某些结构 Foo 的对齐方式与某些类型 T 的对齐方式一样大的当前变通方法是包含一个 [T; 0] 类型的字段,该字段具有大小为零,因此不会影响结构的行为,例如struct Foo { data: A, more_data: B, _align: [T; 0] }

每晚,这可以与 SIMD 类型结合以获得特定的高对齐,因为它们的对齐等于它们的大小(好吧,2 的下一个幂),例如

#[repr(simd)]
struct SixteenBytes(u64, u64);

struct Foo {
    data: A,
    more_data: B,
    _align: [SixteenBytes; 0]
}

huon 的回答很好,但是已经过时了。

从 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>());
}