Image-empty-state.png

Tamir Bahar

JFrog

Generating Generators

Many people in the Go community want Python-style generators. To be able to yield values and maintain the function state. This often causes people to use goroutines and channel to achieve this. But this common pitfall has many issues as it involves the scheduler and abuses goroutines. Getting language support for generators and a yield statement in Go might happen in the future, but we cannot rely on that, and we don’t want to wait.

Luckily, Go already has all the tools we need to roll our own generators. Go’s standard library allows us to parse and analyze our source code, and go:generate allows us to easily trigger code generation to build our generators. That, along with a few goto statements, is all we need to create Python-style generators.

In this talk we’ll go over the core parts of hacking together Go generators. From the basics of stateful-functions, through code analysis, and onto the final code generation. We’ll also see what the issues are with this approach, and why language-level support is still a better option.