Expand description
Specifies the representation of a type.
Written as an outer attribute on a struct, enum or union, repr controls how the
type is laid out in memory. This is needed when passing types across an FFI boundary
or whenever you rely on a specific layout.
The available representations are:
Rust(the default): the layout is unspecified and may change between compilations.C: the layout follows the rules of the C language for the target platform.- The primitive representations (
u8,i32,usize, …): set the discriminant type of an enum. transparent: the type has the same layout and ABI as its only non-zero-sized field.
The align(N) and packed(N) modifiers raise or lower the alignment of a type, respectively.
N must be a power of two no greater than 229. The two modifiers cannot be
applied to the same type, and references to fields of a packed type cannot be created,
since they may be unaligned.
§Examples
#[repr(C, align(16))]
struct Foo {
first: u32,
second: u32,
third: u32,
}
assert_eq!(align_of::<Foo>(), 16);
// 12 bytes of fields, rounded up to a multiple of the alignment.
assert_eq!(size_of::<Foo>(), 16);#[repr(C, packed(2))]
struct Foo {
first: u32,
second: u32,
third: u32,
}
assert_eq!(align_of::<Foo>(), 2);
assert_eq!(size_of::<Foo>(), 12);Foo is laid out according to the C rules and is guaranteed to be 16-byte aligned.
The representation is a property of the type definition, so it does
parameters: below, Foo<u8> and Foo<u64> both use the C representation. Their actual
layouts still differ, because they depend on T.