I have a custom type which internally has a slice of data.
Is it possible, by implementing some functions or an interface that the range operator needs, to iterate (using range) over my custom type?
I have a custom type which internally has a slice of data.
Is it possible, by implementing some functions or an interface that the range operator needs, to iterate (using range) over my custom type?
No, not using range
. range
accepts arrays, slices, strings, maps, and channels, and that's it.
The usual sort of idiom for iterable things (for example a bufio.Scanner
) seems to be
iter := NewIterator(...)
for iter.More() {
item := iter.Item()
// do something with item
}
but there's no universal interface (wouldn't be very useful given the type system anyway) and different types that implement the pattern generally have different names for their More
andItem
methods (for example Scan
and Text
for a bufio.Scanner
)