Today I learned about Go build tags. Here’s some quick notes to help me remember how to use them.
Assume you have directory like so:
$ ls -1
extra.go
go.mod
main.go
And main.go
has contents:
package main
import "fmt"
var numbers = []string{
"one",
"two",
}
func main() {
for _, number := range numbers {
fmt.Println(number)
}
}
And extra.go
has contents:
//go:build extrastuff
package main
func init() {
numbers = append(numbers, "three", "four")
}
If you build without any tags, you get this:
$ go build
$ ./buildtags
one
two
But if you specify the extrastuff
tag, you get:
$ go build --tags=extrastuff
$ ./buildtags
one
two
three
four
If you want to use multiple tags, you can do so like this:
//go:build firstTag || secondTag
← OR - builds when either tag provided//go:build firstTag && secondTag
← AND - builds only when both tags provided
There used to be a syntax like // +build tagName
but that superseded by the //go:build
syntax in Go 1.17.