Golang / GoLang Production Patterns and Web Standards Interview Questions
How do build tags work in Go and when do you use them?
Build constraints (build tags) allow you to include or exclude source files from compilation based on OS, architecture, Go version, or custom conditions. They are used for platform-specific code and integration test separation.
// Modern syntax (Go 1.17+) â //go:build directive // Must be the first non-blank, non-comment line in the file // OS-specific implementation // File: signals_unix.go //go:build linux || darwin package server import "syscall" func shutdownSignals() []os.Signal { return []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP} } // File: signals_windows.go //go:build windows package server func shutdownSignals() []os.Signal { return []os.Signal{os.Interrupt} } // Integration test exclusion // File: integration_test.go //go:build integration package api_test // Run only with: go test -tags integration ./... func TestDatabaseIntegration(t *testing.T) { db := openRealDB(t) // ... } // Constraint operators: // //go:build linux && amd64 â AND // //go:build linux || darwin â OR // //go:build !windows â NOT // //go:build go1.21 â minimum Go version // Filename convention (alternative, no build tag needed): // file_linux.go â only on Linux // file_windows_amd64.go â only on Windows/amd64 // file_test.go â only in test builds
More Related questions...