Build tags
Build tags are comments that include or exclude a file from a build based on OS, architecture, Go version, or a custom name you pass with -tags. They are how one package ships Windows and Linux files without #ifdef.
Detailed Explanation
You have a function that reads a process's CPU time. The Linux implementation uses /proc. The Windows implementation uses a different API. In C you would wrap both in #ifdef. In Go you put them in two files:
//go:build linux
//go:build windows
The compiler compiles exactly one of them for a given GOOS. The package still presents one func cpuTime(). Callers do not see the tag.
Two syntaxes, one meaning. //go:build linux && amd64 is the current form (Go 1.17+). The older // +build linux,amd64 still works. New files should use //go:build. The line must be at the top of the file, followed by a blank line, before package.
Operators. &&, ||, and ! combine tags. unix is a group that matches Linux, macOS, BSD. go1.22 is true when the toolchain is 1.22 or newer. A custom tag such as integration is false unless you build with -tags integration.
File names are implicit tags. foo_linux.go is compiled only on Linux. foo_amd64.go only on amd64. foo_linux_amd64.go is both. foo_test.go is a test file, not a GOOS. Prefer explicit //go:build when the condition is not a simple OS/arch pair, so readers do not have to memorize the name rules.
Custom tags for optional code. Integration tests that need a database often live behind //go:build integration. Default go test ./... skips them. CI runs go test -tags integration ./.... The same pattern works for //go:build tools files that import generators without linking them into the binary.
What it costs. Tags split a type across files. The unused file is not compiled, so you cannot share an unexported helper from cpu_linux.go with cpu_windows.go unless you put the helper in an untagged file. A missing implementation for one GOOS is a compile error on that OS, which is what you want, and a surprise if you only build on your laptop.
Code Examples
go:build linux
//go:build linux
package cpu
func time() (int64, error) {
// read /proc
return 0, nil
}go:build windows
//go:build windows
package cpu
func time() (int64, error) {
// Windows API
return 0, nil
}go:build integration
//go:build integration
package store_test
func TestAgainstPostgres(t *testing.T) {
t.Parallel()
}Common Gotchas
Untagged files in the same package always compile
they must type-check on every OS. Keep OS-specific types out of them.
`-tags` is a list
`go test -tags integration,race` is not the same as the race detector flag `-race`. Custom tags and `-race` are separate.
`ignore` is a built-in tag that is never true
`//go:build ignore` keeps a file in the tree without compiling it, a common pattern for `//go:generate` helpers.