Use //go:build comments and the -tags flag to conditionally compile Go code for specific environments.
Build constraints (build tags) control which Go source files are included in a build based on the target environment. Add a //go:build comment at the top of a file to specify conditions like OS, architecture, or custom tags.
//go:build linux && amd64
// +build linux,amd64
package main
func init() {
// Linux-specific code
}
To build with a custom tag, pass it via the -tags flag:
go build -tags mytag ./cmd/myapp
Build tags act like switches that tell Go to include or ignore specific files depending on where the code is running. You use them to write different code for different operating systems or to enable optional features without changing your main logic. Think of it like having different instruction manuals for different car models in the same box.