Skip to main content
Version: 1.0

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:

from std.iter import Iterator

def preallocate[I: Iterator](mut iter: I) -> List[Int]:
var lower, _upper = iter.bounds()
# Pre-allocate based on estimated iterator length
return List[Int](capacity=lower)

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