Build tags in Go are directives that control whether a source file is included in the build based on the target environment. You place them at the top of a file using the //go:build comment syntax followed by a // +build line for older toolchain compatibility.
//go:build linux && amd64
// +build linux,amd64
package main
func init() {
// Linux-specific code
}
- Add the
//go:builddirective at the very top of the file before the package declaration. - List the conditions (OS, architecture, or custom tags) separated by
&&for AND logic or||for OR logic. - Add the legacy
// +buildline immediately below it to support Go versions older than 1.17. - Run
go buildto compile the project, which will automatically include or exclude files based on these rules.