Tuesday, November 9, 2021

Stateful iterators in Go

I’m writing an insane amount of Go code lately. It’s really unobtrusive, allowing you focus on the problem you have to solve. And I’ve been dabbling with iterators in Go for a while, since I started to used them in Rust – which is so much better than C++ in this regard.

Today, when researching the topic again, I found a very nice article on the matter, exploring a few possibilities. The most performant approach is a stateful iterator, which can be implemented as:

type IterFive struct {
	count int
}

func NewIterFive() IterFive {
	return Iter{}
}

func (it *IterFive) Value() int {
	it.count++
	return it.count - 1
}

func (it *IterFive) Ok() bool {
	return it.count < 5
}

func main() {
	for iter := NewIterFive(); iter.Ok(); {
		println(iter.Value())
	}
}

I’m still unsure whether I should adopt interators instead of simply allocating and returning slices for some functions, but I’m considering it. The main reason would be performance, but it could be qualified as premature in the cases I’m dealing with in Windigo.

No comments: