Golang / Golang Internals and Memory Management Interview Questions
How do build constraints (build tags) work in Go?
Build constraints allow you to conditionally include or exclude Go source files based on the target OS, architecture, Go version, or custom tags. They are essential for platform-specific code, test-only code, and feature flags at build time.
// Modern syntax (Go 1.17+) — //go:build directive
// Place this as the FIRST non-blank, non-comment line
//go:build linux && amd64
package main
// This file is only compiled on Linux/amd64
func platformSpecific() { /* ... */ }
// Combining constraints
//go:build (darwin || linux) && !386
// Custom tags — enable with: go build -tags integration
//go:build integration
package main
func TestIntegration(t *testing.T) { /* runs only with -tags integration */ }
// OS and architecture tags (auto-detected from filename or directive)
// file_linux.go — only on Linux
// file_windows_amd64.go — Windows + amd64
// file_test.go — only in test builds
// Go version constraint
//go:build go1.21
// Negate a tag
//go:build !cgo
// Run tests with a custom tag:
// go test -tags integration ./...
// Build ignoring all tags:
// go build -tags '' ./...
// Legacy syntax (still supported for compatibility):
// // +build linux
// (Note: one blank line between +build and package declaration)The filename convention (_linux.go, _amd64.go) is a shorthand that the Go toolchain parses automatically — equivalent to a //go:build directive. File suffix constraints use underscore-separated GOOS and GOARCH values. If a file has both a filename constraint and a //go:build directive, both must be satisfied.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
