rustalignment

Error: `align` attribute can only be applied to a struct, enum, or union


How can i align member of struct to a specific boundary. One motivation would be to disable false sharing of cache lines.

Consider this example:

use std::sync::atomic::AtomicBool;
pub struct Foo {
    id: String,
    read: AtomicBool,
    #[repr(align(64))]
    write: AtomicBool
}
error[E0517]: attribute should be applied to a struct, enum, function, associated function, or union
 --> src/lib.rs:5:12
  |
5 |     #[repr(align(64))]
  |            ^^^^^^^^^
6 |     write: AtomicBool
  |     ----------------- not a struct, enum, function, associated function, or union

For more information about this error, try `rustc --explain E0517`.

Solution

  • Create a wrapper type:

    use std::sync::atomic::AtomicBool;
    
    #[repr(align(64))]
    struct CacheAligned<T>(T);
    
    #[repr(C)]
    pub struct Foo {
        id: String,
        read: AtomicBool,
        write: CacheAligned<AtomicBool>,
    }
    

    You should also use #[repr(C)] if you are interested in a specific layout; the layout is unspecified otherwise.