Build Tags & Constraints
A Go package is a directory, but not every file in the directory is compiled every time. Build constraints decide per file: this file only on Windows, that one only with cgo, this other one only when the pro tag is set. There is no preprocessor and no #ifdef: the unit of conditional compilation is the whole file.
Two mechanisms
1. File name suffixes. A file named name_GOOS.go, name_GOARCH.go or name_GOOS_GOARCH.go is only compiled for that target: os_linux.go, asm_amd64.go, sys_windows_arm64.go. _test.go files are only compiled by go test.
2. //go:build lines. A comment line before the package clause (followed by a blank line) with a boolean expression:
//go:build linux && (amd64 || arm64) && !purego
package fastpath| Term | True when |
|---|---|
linux, windows, darwin, … |
GOOS matches (unix matches every Unix-like GOOS) |
amd64, arm64, wasm, … |
GOARCH matches |
cgo |
cgo is enabled for this build |
go1.22 |
the Go version is at least 1.22 (all release tags up to the current one are set) |
gc, gccgo |
which compiler |
| any other word | it was passed with -tags word1,word2 |
ignore |
(convention) never set, so the file is never built; used for go run gen.go helper programs |
Operators are &&, ||, ! and parentheses. Old code may also have // +build lines; gofmt keeps them in sync with //go:build, and since Go 1.17 //go:build is the one that counts.
Editions and platforms, for real
mkdir tags && cd tags
go mod init example.com/tags 2>/dev/null
cat > main.go <<'SRC'
package main
import "fmt"
func main() { fmt.Println("edition:", edition, "| platform file:", platformFile) }
SRC
cat > edition_free.go <<'SRC'
//go:build !pro
package main
const edition = "free"
SRC
cat > edition_pro.go <<'SRC'
//go:build pro
package main
const edition = "pro"
SRC
for f in linux windows; do
printf 'package main\n\nconst platformFile = "os_%s.go"\n' $f > os_$f.go
done
cat > os_other.go <<'SRC'
//go:build !linux && !windows
package main
const platformFile = "os_other.go"
SRC
go run .
go run -tags pro .
go list -f '{{.GoFiles}} ignored: {{.IgnoredGoFiles}}' .
GOOS=windows go list -tags pro -f '{{.GoFiles}}' .
GOOS=darwin GOARCH=arm64 go list -f '{{.GoFiles}}' .
go vet -tags pro . && echo "vet ok (pro)"edition: free | platform file: os_linux.go
edition: pro | platform file: os_linux.go
[edition_free.go main.go os_linux.go] ignored: [edition_pro.go os_other.go os_windows.go]
[edition_pro.go main.go os_windows.go]
[edition_free.go main.go os_other.go]
vet ok (pro)
go list -f with GoFiles and IgnoredGoFiles is the honest way to see which files a configuration compiles, for any GOOS/GOARCH/-tags combination, without building anything. Each variant must define every name the rest of the package uses (edition, platformFile), and only one variant may be active at a time; otherwise you get "undefined" or "redeclared" errors for some configurations only.
A model of the file selection
The selection is mechanical, so it fits in a few lines: parse the suffix, evaluate the expression with the active tags. This model reproduces the three go list results above:
const KNOWN_OS = ['linux', 'windows', 'darwin', 'freebsd'];
const KNOWN_ARCH = ['amd64', 'arm64', '386', 'wasm'];
function evalExpr(expr, tags) {
// turn `!a && (b || c)` into JS with each word replaced by true/false
const js = expr.replace(/[A-Za-z0-9_.]+/g, (w) => String(tags.has(w)));
return Function(`return (${js});`)();
}
function selected(files, goos, goarch, extraTags = []) {
const tags = new Set([goos, goarch, ...extraTags]);
if (goos !== 'windows') tags.add('unix');
return Object.entries(files).filter(([name, constraint]) => {
const parts = name.replace(/\.go$/, '').split('_').slice(1);
for (const p of parts) {
if (KNOWN_OS.includes(p) && p !== goos) return false;
if (KNOWN_ARCH.includes(p) && p !== goarch) return false;
}
return constraint === '' || evalExpr(constraint, tags);
}).map(([name]) => name).sort();
}
const files = {
'main.go': '',
'edition_free.go': '!pro',
'edition_pro.go': 'pro',
'os_linux.go': '',
'os_windows.go': '',
'os_other.go': '!linux && !windows',
};
console.log(selected(files, 'linux', 'amd64'));
console.log(selected(files, 'windows', 'amd64', ['pro']));
console.log(selected(files, 'darwin', 'arm64'));[ 'edition_free.go', 'main.go', 'os_linux.go' ]
[ 'edition_pro.go', 'main.go', 'os_windows.go' ]
[ 'edition_free.go', 'main.go', 'os_other.go' ]
Tags and modules
Build tags interact with the module system in one important way: go mod tidy considers every file, under every tag combination (except ignore). A dependency imported only from edition_pro.go is still required in go.mod, so a pro build never fails for lack of a requirement. The flip side: a heavy dependency used behind a rarely-set tag is still in everyone's module graph and go.sum, and still shows up in govulncheck's module results.
Common uses of tags in real projects:
| Tag | Purpose |
|---|---|
integration |
slow tests that need a database: go test -tags integration ./... |
purego |
disable assembly, for portability or debugging (used by x/crypto) |
netgo, osusergo |
pure-Go DNS resolver / user lookup, for static binaries (Cross Builds & cgo) |
pro, enterprise, oss |
editions of one product from one code base |
tools (older) |
a tools.go file importing tools to keep them in go.mod; replaced by the tool directive |
Tip: Editors and gopls build with the default tags only, so files behind a custom tag look "not part of the build". Set
"buildFlags": ["-tags=pro"]in gopls's settings when you work on them (Toolkit).
Test yourself
Which file is compiled only when building for Windows on ARM64?
sys_arm64.gosys_windows_arm64.gowindows/sys.gosys.gowith// windows arm64
What does //go:build !pro on a file mean?
- The file is never built
- The file is built unless
-tags prois passed - The file is only built with -tags pro
- It is a comment with no effect
A dependency is imported only from a file with //go:build pro. Does go mod tidy keep it in go.mod?
- No, tidy only looks at default builds
- Yes, tidy considers all build tags and platforms
- Only if you run tidy -tags pro
- Only for GOOS=linux