Skip to main content
Log in

Mojo struct

InlineArray

struct InlineArray[ElementType: CollectionElement, size: Int, *, run_destructors: Bool = False]

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 CollectionElement trait.

Example:

    # 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
    # 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 (CollectionElement): The type of the elements in the array. Must implement CollectionElement.
  • size (Int): The size of the array. Must be a positive integer constant.
  • run_destructors (Bool): Whether to run destructors on the elements. Defaults to False for backwards compatibility. Will default to True in the future.

Aliases

  • type = array<#lit.struct.extract<:@stdlib::@builtin::@int::@Int size, "value">, :trait<@stdlib::@builtin::@value::@CollectionElement> ElementType>:

Implemented traits

AnyType, CollectionElement, Copyable, ExplicitlyCopyable, Movable, Sized, UnknownDestructibility

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.

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

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

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, *, owned unsafe_assume_initialized: InlineArray[UnsafeMaybeUninitialized[ElementType], size])

Constructs an InlineArray from an InlineArray of UnsafeMaybeUninitialized.

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).

Warning:

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

Args:

  • unsafe_assume_initialized (InlineArray[UnsafeMaybeUninitialized[ElementType], size]): The array of UnsafeMaybeUninitialized elements. All elements must be initialized.

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

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

Example:

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)
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.

@implicit __init__(out self, owned *elems: ElementType)

Constructs an array from a variadic list of elements.

Example:

var arr = InlineArray[Int, 3](1, 2, 3)  # [1, 2, 3]
var arr = InlineArray[Int, 3](1, 2, 3)  # [1, 2, 3]

Args:

  • *elems (ElementType): The elements to initialize the array with. Must match the array size.

__init__(out self, *, owned storage: VariadicListMem[ElementType, origin])

Construct an array from a low-level internal representation.

Args:

  • storage (VariadicListMem[ElementType, origin]): The variadic list storage to construct from. Must match array size.

__copyinit__

__copyinit__(out self, other: Self)

Copy constructs the array from another array.

Creates a deep copy by copying each element individually.

Args:

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

__del__

__del__(owned self)

Deallocates the array and destroys its elements.

This destructor is called automatically when the array goes out of scope. If the array's run_destructors parameter is True, it will call the destructor on each element in the array before deallocating the array's memory.

Example:

var arr = InlineArray[Int, 3](1, 2, 3)
# arr's destructor is called automatically when it goes out of scope
var arr = InlineArray[Int, 3](1, 2, 3)
# arr's destructor is called automatically when it goes out of scope

__getitem__

__getitem__[I: Index](ref self, idx: I) -> ref [self] ElementType

Gets a reference to the element at the given index.

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.

Example:

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
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

Parameters:

  • I (Index): The type parameter representing the index type, must implement Indexer trait.

Args:

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

Returns:

A reference to the element at the specified index.

__getitem__[I: Index, //, idx: I](ref self) -> ref [self] ElementType

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

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.

Example:

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

Parameters:

  • I (Index): The type parameter representing the index type, must implement Indexer trait.
  • idx (I): The compile-time constant index to access. Can be positive (0 to len-1) or negative (-len to -1).

Returns:

A reference to the element at the specified index.

__contains__

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

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

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 both EqualityComparable and CollectionElement traits to support equality comparison.

Example:

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
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

Parameters:

  • T (EqualityComparableCollectionElement): The element type, must implement both EqualityComparable and CollectionElement.

Args:

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

Returns:

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

copy

copy(self) -> Self

Creates a deep copy of the array.

Example:

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

Returns:

A new array containing copies of all elements.

__len__

__len__(self) -> Int

Returns the length of the array.

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

Example:

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

Returns:

The size of the array as an Int.

unsafe_get

unsafe_get[I: Index](ref self, idx: I) -> ref [self] ElementType

Gets a reference to an element without bounds checking.

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

Warning:

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

Example:

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

Parameters:

  • I (Index): A type parameter representing the index type, must implement Indexer trait.

Args:

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

Returns:

A reference to the element at the given index.

unsafe_ptr

unsafe_ptr(ref self) -> UnsafePointer[ElementType, mut=self_is_mut, origin=self_is_origin]

Gets an unsafe pointer to the underlying array storage.

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.

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

Example:

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

Returns:

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