A blog post to describe 3 ways (or 2 alternative ways) to emulate python’s yield in go.

Yield is used to write iterators in python (and other languages. c# added yield in version 2, more than a decade ago). A loop calls a function that calls yield to return the next item in the sequence.

  1. using channels.
  2. using callback function with a closure / same as a continuation or call/cc?
  3. using an iterator object to store state

Eric S. Raymond wrote an evaluation of go from his porting of the code of a project from python which mentions porting python’s iterators.

How does ESR’s method compare is under 2. I think. Todo: link to ESRs info.

Ewen Cheslack-Postava’s discussion on iterator patterns

Here’s the results of running ryszard’s iterator benchmark on my machine, using go 1.13.6

golang-iterators-benchmark-master>go test -bench .
goos: windows
goarch: amd64
pkg: ryszard-iter/golang-iterators-benchmark-master
BenchmarkIntsCallbackIterator-8                      462           2508035 ns/op
BenchmarkDataCallbackIterator-8                      372           2975549 ns/op
BenchmarkIntsChannelIterator-8                         4         298740575 ns/op
BenchmarkDataChannelIterator-8                         4         300250475 ns/op
BenchmarkIntsBufferedChannelIterator-8                 9         111217711 ns/op
BenchmarkDataBufferedChannelIterator-8                10         114300030 ns/op
BenchmarkIntsClosureIterator-8                       418           2812871 ns/op
BenchmarkDataClosureIterator-8                       397           3011335 ns/op
BenchmarkIntStatefulIterator-8                       655           1794547 ns/op
BenchmarkDataStatefulIterator-8                      615           1936387 ns/op
BenchmarkIntStatefulIteratorInterface-8              267           4393849 ns/op
BenchmarkDataStatefulIteratorInterface-8             267           4415787 ns/op
ok      golang-iterators-benchmark-master  22.480s