@align
Add the @align(N) decorator on a struct to specify the minimum alignment in
bytes. The value N must be a positive power of 2.
For example, adding @align(64) on a struct containing an Int (8-byte
aligned) aligns the struct to 64 bytes:
from sys import align_of
@align(64)
struct CacheAligned:
var data: Int
fn main():
print(align_of[CacheAligned]()) # Prints 64The actual alignment will be max(N, natural_alignment), because you cannot
reduce alignment below the struct's natural alignment. For example, @align(1)
on a struct containing an Int (8-byte aligned) will emit a warning and the
struct will remain 8-byte aligned.
Both stack and heap allocations respect @align.
Parametric alignment
The alignment value can also be a struct parameter, enabling generic aligned types:
from sys import align_of
@align(Self.alignment)
struct AlignedBuffer[alignment: Int]:
var data: Int
fn main():
print(align_of[AlignedBuffer[64]]()) # Prints 64
print(align_of[AlignedBuffer[128]]()) # Prints 128The alignment is validated when the struct is instantiated, so invalid values
like AlignedBuffer[3] will produce a compile-time error.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!