Is there a way to make custom data structure that is indexable and hence can be used with for loop

Is there a way to create a custom data structure that can be used with the for loop?

I figured that such data structure needs to be “indexable” given the error I get:

type 'MyCustomType' is not indexable and not a range

So question is, can I also define a custom data type that is “indexable”

By the way I am aware of ability to create a custom iterator that can be used with a while loop but this question is more about exploring and understanding Zig better: what can and cannot be done.

As far as I know, it is not possible to implement some magic method to make your data structure work with a for loop.
According to the docs here, a for loop iterates over slices and arrays, no mention of implementing it for other types are made.
But I’d be glad to be proven wrong.

1 Like

Other than exposing an array or slice, you can expose a range:

I think an iterator is usually the right way if you don’t have a slice/array.

No, you can’t. It’s by design, the whole avoiding hidden control flow principle.
Explicit iterators are the preferred way.

5 Likes

Your data structure also could have a field with a slice that can be used for iteration similar to std.ArrayList’s .items.

Or you could have a method that returns a slice, but if there is no easy way to create such a slice, then iterators may be the best other option.

3 Likes