Talk: Code Generation with Go: Insights from GDG Hamburg Meetup

In June 2022, I presented on code generation using Go’s templating at the GDG Hamburg Meetup. Here’s a recap of what we covered in the 20-minute session.

image

Code Generation Overview

Code generation automates repetitive coding tasks and ensures consistency across a project. While developers are creative problem-solvers, manually handling repetitive tasks isn’t the most efficient use of time. Automated code generation provides speed and consistency where it matters.

Programs excel at repetitive tasks - they’re fast, accurate, and don’t get bored. They’re well-suited for generating code based on specific rules or templates.

How It Works

The basic model for code generation:

[INPUT] --> [GENERATOR] --> [OUTPUT]

For Go, we focused on generating Go code from Go code using built-in tools and templates.

We covered familiar tools like go test, openapi-generator, and Protobuf compiler that generate code from various inputs. Also mentioned hugo and helm for generating static sites and Kubernetes manifests.

We examined stringer - a Go tool that automatically generates methods to satisfy the fmt.Stringer interface for integer types. This demonstrated practical code generation in Go development.

The main part of the talk involved building a simple code generator together. Starting from the stringer example, we developed a generator that automatically implements the String() method for Go types.

Key Points

Resources

All code and examples from the talk are on GitHub. For more details, check out Rob Pike’s article on stringer and Paul Jolly’s talk at GopherCon UK 2019.

We’re hiring at MOIA if you’re interested in Go opportunities.

Thanks to everyone who attended at GDG Hamburg Meetup.

Questions or want to discuss further? Reach out via Twitter or my website.

#Go #Talks