For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
Layout
struct Layout[T: AnyType, *, alignment: Alignment = Alignment.of[T]()]
Describes the shape of a memory allocation for elements of type T.
A Layout pairs the count of elements, held at runtime, with the
alignment of the allocation, carried as a compile-time parameter. Passing
a Layout to alloc and dealloc keeps the size and alignment
requirements explicit and co-located at every call site, preventing
mismatches between allocation and deallocation.
Example:
from std.memory.alloc import alloc, dealloc, Layout
# Allocate room for 8 Int32 values with `Int32`'s natural alignment.
var layout = Layout[Int32](count=8)
var allocation = alloc(layout)
# ... use allocation ...
dealloc(allocation^)
# Over-align the same storage to a 64-byte boundary.
var over_aligned = alloc(
Layout[Int32, alignment = .of_bytes[64]()](count=8)
)
dealloc(over_aligned^)
Parameters
- T (
AnyType): The element type the layout describes. - alignment (
Alignment): Byte alignment of the allocation.
Implemented traits
AnyType,
Copyable,
Deinitable,
ImplicitlyCopyable,
Movable,
RegisterPassable,
TrivialRegisterPassable,
Writable
Methods
__init__
def __init__(*, count: Int) -> Self
Initializes a Layout describing count elements of type T.
Constraints:
alignment must be no smaller than align_of[T](). Alignment
itself enforces the power-of-two requirement.
Args:
- count (
Int): Number of elements of typeTto describe.
single
static def single() -> Self
Creates a Layout for exactly one element of type T.
Example:
from std.memory.alloc import alloc, dealloc, Layout
var layout = Layout[Int64].single()
var allocation = alloc(layout)
allocation.unsafe_ptr().write(0)
dealloc(allocation^)
Returns:
Self: A Layout with count equal to 1.
as_byte_layout
def as_byte_layout(self) -> Layout[UInt8, alignment=alignment]
Converts this layout to an equivalent byte-level layout.
Multiplies the element count by size_of[T]() to express the same
allocation in terms of raw bytes, preserving the alignment.
Returns:
Layout[UInt8, alignment=alignment]: A Layout[Byte, alignment=_] whose count is
self.count() * size_of[T]().
count
def count(self) -> Int
Returns the number of elements described by this layout.
Returns:
Int: The element count passed at construction time.
write_to
def write_to(self, mut writer: T)
Writes a human-readable representation of this layout to writer.
Args:
- writer (
T): The writer to write to.
write_repr_to
def write_repr_to(self, mut writer: T)
Writes a debug representation of this layout to writer.
Args:
- writer (
T): The writer to write to.