Skip to main content

Mojo struct

InlineArray

struct InlineArray[ElementType: Copyable, size: Int]

A fixed-size sequence of homogeneous elements where size is a constant expression.

InlineArray provides a fixed-size array implementation with compile-time size checking. The array size is determined at compile time and cannot be changed. Elements must implement the Copyable trait.

Examples:

# Create array of 3 integers
var arr: InlineArray[Int, 3] = [1, 2, 3]

# Create array filled with value
var filled = InlineArray[Int, 5](fill=42)

# Access elements
print(arr[0])  # Prints 1

Parameters

  • ElementType (Copyable): The type of the elements in the array. Must implement Copyable trait.
  • size (Int): The size of the array. Must be a positive integer constant.

Implemented traits

AnyType, Copyable, Defaultable, DevicePassable, Equatable, Hashable, ImplicitlyCopyable, ImplicitlyDestructible, Iterable, Movable, Sized, Writable

comptime members

device_type

comptime device_type = InlineArray[ElementType, size]

The device-side type for this array.

IteratorType

comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]] = _InlineArrayIter[ElementType, size, iterable_origin]

The iterator type for this array.

Parameters

  • iterable_mut (Bool): Whether the iterable is mutable.
  • iterable_origin (Origin): The origin of the iterable.

type

comptime type = __mlir_type.`!pop.array<#lit.struct.extract<:!lit.struct<@std::@builtin::@int::@Int> size, "_mlir_value">, :trait<@std::@builtin::@value::@Copyable> ElementType>`

The underlying MLIR array type.

Methods

__init__

__init__(out self)

This constructor will always cause a compile time error if used. It is used to steer users away from uninitialized memory.

__init__(out self, *, uninitialized: Bool)

Create an InlineArray with uninitialized memory.

Examples:

var uninitialized_array = InlineArray[Int, 10](uninitialized=True)

Notes: This constructor is unsafe and should be used with caution. The array elements will be uninitialized and accessing them before initialization is undefined behavior.

Args:

  • uninitialized (Bool): A boolean to indicate if the array should be initialized. Always set to True (it's not actually used inside the constructor).

__init__(out self, *, var unsafe_assume_initialized: InlineArray[UnsafeMaybeUninit[ElementType], size])

Constructs an InlineArray from an InlineArray of UnsafeMaybeUninit.

Warning: This is an unsafe constructor. Only use it if you are certain all elements are properly initialized.

Notes: This constructor assumes all elements in the input array are initialized. Using uninitialized elements results in undefined behavior, even for types that are valid for any bit pattern (e.g. Int or Float).

Args:

  • unsafe_assume_initialized (InlineArray): The array of UnsafeMaybeUninit elements. All elements must be initialized.

__init__[batch_size: Int = 64](out self, *, fill: ElementType)

Constructs an array where each element is initialized to the supplied value.

Examples:

var filled = InlineArray[Int, 5](fill=42)  # [42, 42, 42, 42, 42]

# For large arrays, consider adjusting batch_size to balance
# compile time and runtime performance:
var large = InlineArray[Int, 10000].__init__[batch_size=32](fill=0)

Notes:

  • Full unrolling with large arrays (>2k elements) can cause significant compiler slowdowns.
  • Using batch_size=64 balances AVX512 efficiency and instruction cache usage.
  • For very large arrays, using smaller batch sizes (e.g., 32 or 16) can further improve compilation speed while still maintaining good runtime performance.

Parameters:

  • batch_size (Int): The number of elements to unroll for filling the array. Default is 64, which optimizes for AVX512 operations on modern CPUs. For large arrays (>2k elements), this batched approach significantly improves compile times compared to full unrolling while maintaining good runtime performance.

Args:

  • fill (ElementType): The element value to fill each index with.

__init__(out self, var *elems: ElementType, *, __list_literal__: Tuple[])

Constructs an array from a variadic list of elements.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]

Args:

  • *elems (ElementType): The elements to initialize the array with. Must match the array size.
  • list_literal (Tuple): Specifies that this constructor can be used for list literals.

__init__[origin: MutOrigin, //](out self, *, var storage: VariadicList[ElementType, True])

Construct an array from a low-level internal representation.

Parameters:

  • origin (MutOrigin): The origin of the storage being passed in.

Args:

  • storage (VariadicList): The variadic list storage to construct from. Must match array size.

__init__(out self, *, copy: Self)

Copy constructs the array from another array.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]
var copy = arr.copy()  # Creates new array [1, 2, 3]

Args:

  • copy (Self): The array to copy from.

__init__(out self, *, deinit take: Self)

Move constructs the array from another array.

Notes: Moves the elements from the source array into this array.

Args:

  • take (Self): The array to move from.

__del__

__del__(deinit self)

Deallocates the array and destroys its elements.

__getitem__

__getitem__(ref self, idx: T) -> ref[size] ElementType

Gets a reference to the element at the given index.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]
print(arr[0])   # Prints 1 - first element
print(arr[1])   # Prints 2 - second element
print(arr[-1])  # Prints 3 - last element
print(arr[-2])  # Prints 2 - second to last element

Notes: This method provides array-style indexing access to elements in the InlineArray. It supports both positive indices starting from 0 and negative indices counting backwards from the end of the array. The index is bounds-checked at runtime.

Args:

  • idx (T): The index to access. Can be positive (0 to len-1) or negative (-len to -1).

Returns:

ref: A reference to the element at the specified index.

__eq__

__eq__(self, other: Self) -> Bool where conforms_to(ElementType, AnyType & ImplicitlyDestructible & Equatable)

Compares two arrays for equality.

Args:

  • other (Self): The other array to compare against.

Returns:

Bool: True if all elements are equal, False otherwise.

__ne__

__ne__(self, other: Self) -> Bool where conforms_to(ElementType, AnyType & ImplicitlyDestructible & Equatable)

Compares two arrays for inequality.

Args:

  • other (Self): The other array to compare against.

Returns:

Bool: True if any elements are not equal, False otherwise.

__contains__

__contains__[T: Equatable & Copyable, //](self: InlineArray[T, size], value: T) -> Bool

Tests if a value is present in the array using the in operator.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]
print(3 in arr)  # Prints True - value exists
print(4 in arr)  # Prints False - value not found

Notes: This method enables using the in operator to check if a value exists in the array. It performs a linear search comparing each element for equality with the given value. The element type must implement the Equatable and Copyable traits to support equality comparison.

Parameters:

  • T (Equatable & Copyable): The element type, must implement both Equatable and Copyable.

Args:

  • value (T): The value to search for.

Returns:

Bool: True if the value is found in any position in the array, False otherwise.

get_type_name

static get_type_name() -> String

Gets the name of the host type (the one implementing this trait).

Returns:

String: The host type's name.

__getitem_param__

__getitem_param__[idx: T](ref self) -> ref[idx] ElementType

Gets a reference to the element at the given index with compile-time bounds checking.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]
print(arr[0])   # Prints 1 - first element
print(arr[-1])  # Prints 3 - last element

Notes: This overload provides array-style indexing with compile-time bounds checking. The index must be a compile-time constant value. It supports both positive indices starting from 0 and negative indices counting backwards from the end of the array.

Parameters:

  • idx (T): The compile-time constant index to access. Can be positive (0 to len-1) or negative (-len to -1).

Returns:

ref: A reference to the element at the specified index.

__len__

__len__(self) -> Int

Returns the length of the array.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]
print(len(arr))  # Prints 3

Notes: The length is a compile-time constant value determined by the size parameter used when creating the array.

Returns:

Int: The size of the array as an Int.

__hash__

__hash__[H: Hasher](self, mut hasher: H) where conforms_to(ElementType, AnyType & Hashable)

Hashes the elements of the array using the given hasher.

Parameters:

  • H (Hasher): The hasher type.

Args:

  • hasher (H): The hasher instance.

unsafe_get

unsafe_get(ref self, idx: T) -> ref[size] ElementType

Gets a reference to an element without bounds checking.

Examples:

var arr: InlineArray[Int, 3] = [1, 2, 3]
print(arr.unsafe_get(0))  # Prints 1

Warning: This is an unsafe method. No bounds checking is performed. Using an invalid index will cause undefined behavior. Negative indices are not supported.

Notes: This is an unsafe method that skips bounds checking for performance. Users should prefer __getitem__ instead for safety.

Args:

  • idx (T): The index of the element to get. Must be non-negative and in bounds. Using an invalid index will cause undefined behavior.

Returns:

ref: A reference to the element at the given index.

unsafe_ptr

unsafe_ptr[origin: Origin[mut=origin.mut], address_space: AddressSpace, //](ref[size, origin._mlir_origin] self) -> UnsafePointer[ElementType, origin, address_space=address_space]

Gets an unsafe pointer to the underlying array storage.

Examples:

var arr:InlineArray[Int, 3] = [1, 2, 3]
var ptr = arr.unsafe_ptr()
print(ptr[0])  # Prints 1

Warning: This is an unsafe method. The returned pointer:

  • Becomes invalid if the array is moved
  • Must not be used to access memory outside array bounds
  • Must be refreshed after any operation that could move the array

Notes: Returns a raw pointer to the array's memory that can be used for direct memory access. The pointer inherits mutability from the array reference.

Parameters:

  • origin (Origin): The origin of the reference to self.
  • address_space (AddressSpace): The address space of the array.

Returns:

UnsafePointer: An UnsafePointer to the underlying array storage. The pointer's mutability matches that of the array reference.

write_to

write_to(self, mut writer: T) where conforms_to(ElementType, AnyType & ImplicitlyDestructible & Writable)

Writes the InlineArray representation to a Writer.

Args:

  • writer (T): The object to write to.

write_repr_to

write_repr_to(self, mut writer: T) where conforms_to(ElementType, AnyType & ImplicitlyDestructible & Writable)

Writes the repr representation of this InlineArray to a Writer.

Args:

  • writer (T): The object to write to.

__iter__

__iter__(ref self) -> _InlineArrayIter[ElementType, size, origin_of(self)]

Iterate over elements of the array, returning immutable references.

Returns:

_InlineArrayIter: An iterator of immutable references to the array elements.

__reversed__

__reversed__(ref self) -> _InlineArrayIter[ElementType, size, origin_of(self), False]

Iterate over elements of the array in reverse order, returning immutable references.

Returns:

_InlineArrayIter: An iterator of immutable references to the array elements in reverse order.

Was this page helpful?