liveBook · Manning

Build tag

As explained in 100 Go Mistakes and How to Avoid Them

A build tag is a Go source-selection constraint that controls whether a file is included in a build or test invocation.

A common mistake is assuming that supplying a tag runs only tagged tests. A build tag is a special comment at the beginning of a Go file, followed by an empty line, that controls whether the file enters a build or test invocation. Untagged files remain included when a matching tag is supplied. section 11.1.1

Use build tags when you need to:

  • Select implementation files conditionally, such as including a file only when cgo is enabled. section 11.1.1
  • Classify integration tests with //go:build integration. Running go test without tags omits the file; running with --tags=integration includes it alongside untagged tests. section 11.1.1
  • Run only one category by adding //go:build !integration to unit-test files, so those files are excluded when integration is enabled. section 11.1.1
  • Exclude tests from race-enabled builds with //go:build !race when they behave incompatibly with race detection. section 11.2

Tagged versus untagged tests

With an integration-tagged TestInsert and an untagged TestContract, go test -v . runs only TestContract. Running go test --tags=integration -v . runs both. If silent omission is risky, an environment-variable guard can keep the test visible and call t.Skip("skipping integration test") when INTEGRATION is not true. section 11.1.1 section 11.1.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains placement, tag matching, negation, and command effects, but stops short of a full constraint-expression treatment.
Examples
Demonstrates cgo, integration, !integration, and !race constraints alongside go test commands and skipped-test output.
What it assumes
Assumes familiarity with Go files and go test; teaches build-constraint placement and tagged test selection.
What you can do after
Operate/configure Go builds and tests by selecting files with tags and recognizing when untagged tests remain included.
How it connects
Connects conditional compilation, integration testing, environment variables, and race detection through source-file selection.

Also explained in

Compare how 3 books explain build tag →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.