Code Generation

Develop code generation tool for Golang

In my previous blog post, we discussed one of my favourite code generation tools for Go. We found that they can be used to automate our trivial development tasks or even introduce features like generics and queries. Lets explore how to create our own tool. Introduction The Go generate subcommand is a program that scans for special comments in your Go source code. The comment declares a command that should be executed.

Generics in Golang

In the article we will take the advantage of [generics] even that they are not first citizen in Go. We will explore gen and genny command line tools. Gen Gen is a code generation tool that brings some generic query functions. It uses annotations to add this functionality to any structure. The generated code is part of your package and does not have any external dependencies. This approach avoids any reflection and produces an efficient concrete implementation for any annotated type.

Reusing source code with Go templates

In one of my previous blog posts, we discovered go generate command line tool. Lets take the next step and evaluate its advanced benefits to generate a source code by using our own templates. We will explore gotemplate command line tool. Overview This command line tool manages package based Go templates using go generate. By default it provides a set of templates that can be used out of the box:

Golang code generation

Programs that produce source code are important elements in software engineering. Since Go 1.4, the language ecosystem includes a command line tool that makes it easier to run such tools. It’s called go generate. It scans for special comments in Go source code that identify general commands to run: //go:generate <subcommand> <arguments> Go generate is not part of go build. It does not do dependency analysis and must be run explicitly before running go build.