错误:`align`属性只能应用于结构体、枚举或联合

问题描述 投票:0回答:1

如何将结构体成员对齐到特定边界。动机之一是禁用错误共享。

考虑这个例子:

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`.
rust alignment
1个回答
0
投票

创建包装类型:

use std::sync::atomic::AtomicBool;

#[repr(align(64))]
struct CacheAligned<T>(T);

#[repr(C)]
pub struct Foo {
    id: String,
    read: AtomicBool,
    write: CacheAligned<AtomicBool>,
}

如果您对特定布局感兴趣,还应该使用

#[repr(C)]
;否则布局未指定。

© www.soinside.com 2019 - 2024. All rights reserved.