Conditional compilation with build tags
suggest changeBuild constraints let the Go tool include different source files for different targets or build configurations.
Specify a constraint near the beginning of a file, before the package clause, and follow it with a blank line.
A typical use is to provide two implementations of the same function and select one with a custom tag.
For example, consider three files in one directory.
foo_alt.go
//go:build alt
package main
import "fmt"
func foo() {
fmt.Printf("This is alternative foo\n")
}
foo.go
//go:build !alt
package main
import "fmt"
func foo() {
fmt.Printf("This is regular foo\n")
}
main.go
package main
func main() {
foo()
}
Compiling without any build tags:
> go build -o main .
> ./main
This is regular foo
Compiling with alt build tag:
> go build -tags alt -o main_alt .
> ./main_alt
This is alternative foo
With -tags=alt, the tool includes foo_alt.go and excludes foo.go. Without
that tag, it does the reverse. The -tags option is also available to commands
such as go run, go install, and go test.
Specifying multiple tags
You can specify multiple build constraints (tags):
//go:build ((tag1 && tag2) || (tag3 && !tag4)) && tag5
package foo
This expression requires tag5 and either both tag1 and tag2, or tag3
without tag4. Pass multiple enabled tags as a comma-separated list, for
example go build -tags=tag1,tag2,tag5.
Ignoring files (excluding from compilation)
//go:build ignore
package foo
Predefined build tags
The Go toolchain defines tags for the current build, including:
- the target architecture, such as
amd64,arm64, orriscv64 - the target operating system, such as
windows,darwin, orlinux cgowhen cgo is enabled- the compiler, such as
gcorgccgo - release tags such as
go1.25, which are satisfied by that release and later releases
Using file name in place of a build tag
Certain file-name suffixes add implicit constraints. For example,
foo_windows.go is included only when GOOS=windows, while
foo_linux_amd64.go requires both Linux and AMD64.
Pitfalls
The following doesn't work as expected:
//go:build alt
package main
func foo() {
fmt.Printf("This is alternative foo\n")
}
The constraint is too close to the package clause and is not recognized. Add a blank line:
//go:build alt
package main
Optimized implementations for specific architectures