3 ms·
I think more idiomatic go for the first case would be: getNext := iterableThing.Iterator() for next, ok := getNext(); ok; next, ok = getNext() {
by Kamq 3y ago
I think more idiomatic go for the first case would be:
getNext := iterableThing.Iterator()
for next, ok := getNext(); ok; next, ok = getNext() {
...
}
Which, yeah, the range cleans it up a bit, but it's not doing quite as much work as you're implying.
- davenoul 3y agoDon't forget that the important bit in Go is readability of the code. To me the range form is much easier to reason about than this for loop.
- Kamq 3y agoIf we're going for readability instead of trying to stick to the case presented above, I'd go with: for i.HasNext() { current := i.GetNext() ... } And just mutate the internal state of the struct. Probably throw it behind some sort of interface like: type Iterator[T any] interface { // feel free to strip out the generic HasNext() bool // if you really only have one type GetNext() T // you do this with } I think this still loses to ranging over a function, but I still think it should be compared to what you can do with the current language as opposed to what was originally posted.