Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to align a struct to a 16 byte boundary in Rust. It seems possible to give hints about alignment through the repr attribute, but it doesn't support this exact use case.

A functional test of what I'm trying to achieve is a type Foo such that

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

or alternatively, a struct Bar with a field baz such that

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

always prints a number divisible by 16.

Is this currently possible in Rust? Are there any work-arounds?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
892 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...