Mojo struct
VariadicList
@register_passable(trivial)
struct VariadicList[type: AnyTrivialRegType]
A utility class to access homogeneous variadic function arguments.
VariadicList
is used when you need to accept variadic arguments where all
arguments have the same type. Unlike VariadicPack
(which is heterogeneous),
VariadicList
requires all elements to have the same concrete type.
At runtime, VariadicList
is treated as a homogeneous array. Because all
the elements have the same type, each element has the same size and memory
layout, so the compiler can generate code that works to access any index
at runtime.
Therefore, indexing into VariadicList
can use runtime indices with regular
for
loops, whereas indexing into VariadicPack
requires compile-time
indices using @parameter for
loops.
For example, in the following function signature, *args: Int
creates a
VariadicList
because it uses a single type Int
instead of a variadic type
parameter. The *
before args
indicates that args
is a variadic argument,
which means that the function can accept any number of arguments, but all
arguments must have the same type Int
.
fn sum_values(*args: Int) -> Int:
var total = 0
# Can use regular for loop because args is a VariadicList
for i in range(len(args)):
total += args[i] # All elements are Int, so uniform access
return total
def main():
print(sum_values(1, 2, 3, 4, 5))
fn sum_values(*args: Int) -> Int:
var total = 0
# Can use regular for loop because args is a VariadicList
for i in range(len(args)):
total += args[i] # All elements are Int, so uniform access
return total
def main():
print(sum_values(1, 2, 3, 4, 5))
Parameters
- type (
AnyTrivialRegType
): The type of the elements in the list.
Fields
- value (
Variadic[type]
): The underlying storage for the variadic list.
Implemented traits
AnyType
,
Copyable
,
Movable
,
Sized
,
UnknownDestructibility
Aliases
IterType
alias IterType = _VariadicListIter[type]
Methods
__init__
@implicit
__init__(*value: type) -> Self
Constructs a VariadicList from a variadic list of arguments.
Args:
- *value (
type
): The variadic argument list to construct the variadic list with.
__getitem__
__getitem__[I: Indexer](self, idx: I) -> type
Gets a single element on the variadic list.
Parameters:
- I (
Indexer
): A type that can be used as an index.
Args:
- idx (
I
): The index of the element to access on the list.
Returns:
type
: The element on the list corresponding to the given index.
__len__
__len__(self) -> Int
Gets the size of the list.
Returns:
Int
: The number of elements on the variadic list.
__iter__
__iter__(self) -> _VariadicListIter[type]
Iterate over the list.
Returns:
_VariadicListIter
: An iterator to the start of the list.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!