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