Skip to main content
Log in

Mojo struct

InlineArray

struct InlineArray[ElementType: Copyable & Movable, 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.

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
# 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 & Movable): 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::@Copyable, @stdlib::@builtin::@value::@Movable> ElementType>:

Implemented traits

AnyType, 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.

Examples:

var uninitialized_array = InlineArray[Int, 10](uninitialized=True)
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, *, owned unsafe_assume_initialized: InlineArray[UnsafeMaybeUninitialized[ElementType], size])

Constructs an InlineArray from an InlineArray of UnsafeMaybeUninitialized.

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

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

Examples:

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.

Notes: 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.

Examples:

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

Notes: 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.

__getitem__

__getitem__[I: Index](ref self, idx: I) -> ref [self] 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
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.

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.

Examples:

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

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:

  • 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: EqualityComparable & Copyable & Movable, //](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
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 both EqualityComparable and CollectionElement traits to support equality comparison.

Parameters:

  • T (EqualityComparable & Copyable & Movable): 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.

Examples:

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.

Examples:

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

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

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.

Examples:

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

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.

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.

Examples:

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

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.

Returns:

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