Golang build tags

Go compiler is capable of compiling source code for different platforms in any development environment (which, apparently, is a big deal and not that common). When your code is targeting multiple architectures, there might be parts of the code tailored for each one of them. Two options exist for defining such alternative code:

However, build tags can be used for other purposes as well. One of the more common ones is separating different test files into groups so that all files with unit tests

// +build unit

can be run with go test -tags unit.

When we first started using this technique it was excellent, but later something happened and some test files were getting omitted. The reason was a missing blank line after the build tag. This tiny detail is documented in the go/build package but it is easily overlooked and not easy to look for.

Quite frankly, it seems rather odd that an empty line is required. The documentation says:

To distinguish build constraints from package documentation, a series of build constraints must be followed by a blank line.

In the simplest case a build tag is followed by a package declaration. There’s no way those two could get mixed up, but a package declaration might be preceded by its documentation, i.e. a comment. Even then build tags need to start with +build which cannot be a part of package documentation, because that must begin with the words “Package xyz”.

An important note is that this is not caught by go fmt which reformats the source code according to the official style guide. Te tool which can detect this is go vet.

The lesson here is: if in doubt about canonical syntax or confused by standard Go tools, run go fmt and go vet. They will get you a level playing field and quite possibly fix your mistake.

We're looking for developers to help us save energy

If you're interested in what we do and you would like to help us save energy, drop us a line at jobs@enectiva.cz.

comments powered by Disqus