Skip to main content

Mojo trait

Iterator

The Iterator trait describes a type that can be used as an iterator, e.g. in a for loop.

Implemented traits

AnyType, ImplicitlyDestructible, Movable

comptime members

Element

comptime Element

Required methods

__init__

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

Create a new instance of the value by moving the value of another.

Args:

  • take (_Self): The value to move.

Returns:

_Self

__next__

__next__(mut self: _Self) -> _Self.Element

Returns the next element from the iterator.

Returns:

_Self.Element: The next element. Raises:

StopIteration if there are no more elements.

Provided methods

bounds

bounds(self: _Self) -> Tuple[Int, Optional[Int]]

Returns bounds [lower, upper] for the remaining iterator length.

This helps collections pre-allocate memory when constructed from iterators. The default implementation returns (0, None).

Safety:

If the upper bound is not None, implementations must ensure that lower <= upper. The bounds are hints only - iterators may not comply with them. Never omit safety checks when using bounds to build collections.

Examples:

def to_int_list[I: Iterable](iter: I) -> List[Int]:
    var lower, _upper = iter.bounds()
    var list = List[Int](capacity=lower)
    for element in iter:
        list.append(rebind[Int](element))
    return list^

Returns:

Tuple: A tuple where the first element is the lower bound and the second is an optional upper bound (None means unknown or upper > Int.MAX).

Was this page helpful?