Review build constraints and generated files
Review build constraints and generated files
Build constraints choose source files for a particular build. A //go:build expression belongs near the top of a file before the package clause, followed by a blank line. GOOS and GOARCH, filename suffixes and explicit -tags can affect selection. go generate runs explicit generation directives; go build does not run generators automatically.
Use a fresh directory for each example, create the listed files (labels are not file contents), and run the commands in a POSIX shell. Use Go 1.23+, local toolchain, and Python 3 only for the synthetic proxy examples. For isolation, set GOWORK=off, GOTOOLCHAIN=local, GOPROXY=off and GOSUMDB=off for these local labs only; use a fresh GOMODCACHE per lab. Proxy examples override GOPROXY to a local file URL. Do not copy disabled checksum settings to real projects.
--- go.mod ---module example.test/app
go 1.23.0
--- main.go ---package main
import "fmt"
func main() { fmt.Println(mode()) }
--- default.go ---//go:build !demo
package main
func mode() string { return "normal" }
--- demo.go ---//go:build demo
package main
func mode() string { return "demo" }
--- Commands (shell, from project root) ---go run .go run -tags=demo .Exactly one definition of mode is selected for each command. Test both configurations. Filename suffixes such as _linux.go also restrict selection. Do not confuse build tags with runtime configuration.
Expected output:
normaldemoGenerate source explicitly
--- go.mod ---module example.test/app
go 1.23.0
--- main.go ---package main
//go:generate sh gen.shimport "fmt"
func main() { fmt.Println(label) }
--- gen.sh ---printf '// Code generated by gen.sh; DO NOT EDIT.\npackage main\nconst label = "generated"\n' > generated.gogofmt -w generated.go
--- Commands (shell, from project root) ---go generate ./...go run .The local generator creates a Go source file with the conventional generated-code marker. Inspect generation directives before running them because they execute commands. Keep generation reproducible and decide whether generated files are committed. This simple generator uses a shell, not external tooling.
Expected output:
generatedTry it locally
Create two files selected by the tag feature and its negation. Print off without the tag and on with -tags=feature.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Modules and workspaces 10: Review build constraints and generated files
Check the lesson objective before moving on.
Does go build execute go:generate directives automatically?
Which command enables a custom build tag demo?