How to implement the Iterator trait when iterating over some internal storage

I want to build an iterator that iterates over some internal storage, say, a list and returns pointers to the elements.

I saw that the Iterator trait requires an alias Element to be specified in the iterator struct. This alias then specifies the return type of the __next__ function.

Specifying the return type via an alias is difficult if the origin of the elements is not known at compile time. Consider this example:

struct Foo(Copyable, Iterator, Movable):
    alias Element = Int
    var _data: List[Int]
    var _index: Int

    fn __init__(out self, data: List[Int]):
        self._data = data
        self._index = -1

    fn __has_next__(self) -> Bool:
        return self._index < len(self._data) - 1

    fn __next__(mut self) -> Pointer[Self.Element, __origin_of(self._data)]:
        self._index += 1
        return Pointer(to=self._data[self._index])

    fn __iter__(self) -> Self:
        return self

The return type requires the origin of self._data. However, this origin is not available at compile time.
How could I solve this problem? (The example above works if the Iterator trait is not specified. I am aware that Element should be a pointer type actually…)

As a tag-on: is the iterator trait currently actually used anywhere? (Is it importent to implement it?)

Hi Samufi,

I don’t think we have a good answers for this yet. This is something I faced when putting together the basic iterator type we have now. We’ll need a way to make the returned origin be an associated alias on the trait, but lack the ability to disassociate it from the self object type. This is something that could be added to the origin system someday, but we haven’t had time to invest in it yet. :frowning:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.