Build Tags
Start with Build Tags
Learn build tags through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of build tags.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Build constraints can select Go source files for a platform, feature or development scenario. A constraint line such as //go:build linux must appear near the beginning of a source file before its package declaration.
The example uses runtime platform detection as a runnable contrast; compile-time build tags require separate files, shown below.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Platform-specific source files
// file: platform_linux.go
//go:build linux
package main
func platform() string { return "linux" }// file: platform_other.go
//go:build !linux
package main
func platform() string { return "other" }Create a third main.go that prints platform(). Both files belong in the same package; exactly one implementation is selected for these conditions.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("Platform known:", runtime.GOOS != "")
fmt.Println("Platform-specific code can use //go:build constraints")
}
Output
Platform known: true
Platform-specific code can use //go:build constraintsTrace what the program does
Runtime.GOOS is populated, so the first line prints true. Runtime checks and compile-time build constraints solve different problems.
Avoid common mistakes
- A build tag selects files before compilation; it is not a normal if statement.
- Keep default and platform-specific declarations compatible across selected file sets.
Try it yourself
Create a small module with the two files shown, then run it on different GOOS targets.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Build Tags in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.