Golang Build & Run Tooling Quiz
35 comprehensive questions on Go's build and run tooling, covering go build, go run, go test, cross-compiling, and build tags — with 15 code examples demonstrating practical build configurations and testing scenarios.
Question 1
What does the 'go build' command do?
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
// Command line:
// go build hello.go
// or
// go build .
// or
// go build -o myapp .
// This creates an executable binaryQuestion 2
How do you specify the output filename with go build?
// Build with custom output name
// go build -o myapp main.go
// Build entire package
// go build -o server .
// Build for current directory
// go build
// Creates executable with directory name
// Cross-platform naming
// On Windows: go build -o app.exe .
// On Linux/Mac: go build -o app .Question 3
What is the difference between 'go build' and 'go run'?
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
// go run main.go
// Compiles and runs in one step, no binary created
// go build main.go
// Creates executable binary
// ./main (or main.exe on Windows)
// go run is equivalent to:
// go build -o /tmp/go-run-123 main.go
// /tmp/go-run-123
// rm /tmp/go-run-123Question 4
How do you build for a different operating system?
// Build for Linux on AMD64
// GOOS=linux GOARCH=amd64 go build .
// Build for Windows on AMD64
// GOOS=windows GOARCH=amd64 go build .
// Build for macOS on ARM64 (Apple Silicon)
// GOOS=darwin GOARCH=arm64 go build .
// Build for Linux on ARM (Raspberry Pi)
// GOOS=linux GOARCH=arm go build .
// Check current values
// go env GOOS GOARCHQuestion 5
How do you run Go tests?
package main
import "testing"
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
// Command line:
// go test
// go test -v
// go test -run TestAdd
// go test ./...Question 6
What are build tags and how do you use them?
// +build linux
package main
import "fmt"
func main() {
fmt.Println("This only compiles on Linux")
}
// Alternative syntax:
//go:build linux
package main
// Usage:
// go build . // Only builds on Linux
// GOOS=linux go build . // Forces Linux build
// Multiple tags:
// +build linux darwin
//go:build linux || darwinQuestion 7
How do you run verbose tests?
func TestExample(t *testing.T) {
t.Log("This will only show with -v")
// Test logic
}
// Command line:
// go test -v
// Output:
// === RUN TestExample
// file_test.go:4: This will only show with -v
// --- PASS: TestExample (0.00s)
// PASS
// Without -v:
// PASSQuestion 8
How do you build for multiple platforms at once?
#!/bin/bash
# Build script for multiple platforms
platforms="linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64"
for platform in $platforms; do
IFS='/' read -r -a array <<< "$platform"
GOOS="${array[0]}"
GOARCH="${array[1]}"
output_name="myapp-${GOOS}-${GOARCH}"
if [ "$GOOS" = "windows" ]; then
output_name+='.exe'
fi
echo "Building for $GOOS/$GOARCH..."
GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name .
echo "Created $output_name"
doneQuestion 9
How do you run specific tests?
func TestAdd(t *testing.T) {
// Test addition
}
func TestSubtract(t *testing.T) {
// Test subtraction
}
func TestMultiply(t *testing.T) {
// Test multiplication
}
// Run specific test:
// go test -run TestAdd
// Run tests matching pattern:
// go test -run "Test(Add|Subtract)"
// Run all tests in package:
// go testQuestion 10
How do you create build tags for different environments?
//go:build debug
package main
import "fmt"
func main() {
fmt.Println("Debug mode enabled")
// Additional debug logging
}
//go:build !debug
package main
import "fmt"
func main() {
fmt.Println("Production mode")
// Optimized production code
}
// Build commands:
// go build -tags debug .
// go build . // Production buildQuestion 11
How do you run benchmarks in Go?
package main
import "testing"
func Fibonacci(n int) int {
if n <= 1 {
return n
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
func BenchmarkFibonacci(b *testing.B) {
for i := 0; i < b.N; i++ {
Fibonacci(10)
}
}
// Command line:
// go test -bench=.
// go test -bench=BenchmarkFibonacci
// go test -bench=. -benchmemQuestion 12
How do you build statically linked binaries?
// Build statically linked binary
// CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' .
// For scratch Docker images
// CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-extldflags "-static"' .
// Check if binary is statically linked
// ldd ./myapp
// Should show "not a dynamic executable" or "statically linked"
// On macOS:
// go build -ldflags '-extldflags "-static"' .Question 13
How do you use build tags for optional features?
//go:build json
package config
import "encoding/json"
func LoadJSON(data []byte) (Config, error) {
var c Config
return c, json.Unmarshal(data, &c)
}
//go:build !json
package config
func LoadJSON(data []byte) (Config, error) {
return Config{}, fmt.Errorf("JSON support not compiled in")
}
// Usage:
// go build . // No JSON support
// go build -tags json . // With JSON supportQuestion 14
How do you run tests with race detection?
func TestConcurrentMap(t *testing.T) {
m := make(map[int]int)
// This might have race conditions
go func() {
m[1] = 1
}()
go func() {
m[2] = 2
}()
// Wait
time.Sleep(time.Millisecond)
}
// Command line:
// go test -race
// Output: ==================
// WARNING: DATA RACE
// ...
// ==================Question 15
How do you build with custom ldflags?
// Set version info
// go build -ldflags "-X main.version=1.2.3 -X main.buildTime=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" .
// Strip debug info for smaller binaries
// go build -ldflags "-s -w" .
// In code:
var (
version string
buildTime string
)
func main() {
fmt.Printf("Version: %s, Built: %s\n", version, buildTime)
}Question 16
How do you run tests in parallel?
func TestParallel1(t *testing.T) {
t.Parallel() // Mark as parallel
// Test logic
}
func TestParallel2(t *testing.T) {
t.Parallel() // Mark as parallel
// Test logic
}
// Command line:
// go test -parallel 4 // Run 4 tests in parallel
// Default is GOMAXPROCS
// Package level parallel limit
func TestMain(m *testing.M) {
// Setup
code := m.Run() // Runs tests
// Cleanup
os.Exit(code)
}Question 17
How do you create build tags for operating system detection?
//go:build windows
package main
import (
"fmt"
"os/exec"
)
func openBrowser(url string) error {
return exec.Command("cmd", "/c", "start", url).Run()
}
//go:build linux || darwin
package main
import (
"fmt"
"os/exec"
)
func openBrowser(url string) error {
return exec.Command("xdg-open", url).Run()
}
// Usage:
// go build . // Uses appropriate implementationQuestion 18
How do you run tests with coverage?
func TestAdd(t *testing.T) {
if Add(2, 3) != 5 {
t.Fail()
}
}
func TestSubtract(t *testing.T) {
if Subtract(5, 3) != 2 {
t.Fail()
}
}
// Command line:
// go test -cover
// go test -coverprofile=coverage.out
// go tool cover -html=coverage.out
// Coverage output:
// PASS
// coverage: 75.0% of statementsQuestion 19
How do you build with specific Go versions?
// Specify Go version in go.mod
module example.com/myapp
go 1.21
// Or use GOTOOLCHAIN
// GOTOOLCHAIN=go1.21.0 go build .
// Check version
// go version
// Output: go version go1.21.0 ...
// Build with specific toolchain
// go build -ldflags "-X 'main.GoVersion=$(go version)'" .Question 20
How do you use build tags for architecture-specific code?
//go:build amd64
package mathops
func Add(a, b int64) int64 {
// AMD64 optimized version
return a + b // Could use SIMD instructions
}
//go:build arm64
package mathops
func Add(a, b int64) int64 {
// ARM64 optimized version
return a + b // ARM-specific optimizations
}
// Usage:
// GOARCH=amd64 go build . // Uses AMD64 version
// GOARCH=arm64 go build . // Uses ARM64 versionQuestion 21
How do you run integration tests separately from unit tests?
// Unit test file: math_test.go
func TestAdd(t *testing.T) {
// Unit test
}
// Integration test file: math_integration_test.go
//go:build integration
func TestDatabaseConnection(t *testing.T) {
// Integration test
}
// Command line:
// go test . // Runs unit tests only
// go test -tags integration . // Runs integration tests
// Or use build constraints:
// +build integration
func TestExternalAPI(t *testing.T) {
// Integration test
}Question 22
How do you create reproducible builds?
# Reproducible build script
#!/bin/bash
# Set consistent environment
unset GOPATH
unset GOBIN
export CGO_ENABLED=0
export GOOS=linux
export GOARCH=amd64
# Use specific Go version
# GOTOOLCHAIN=go1.21.0
# Build with consistent flags
go build \
-a \
-ldflags "-s -w -X main.version=1.0.0" \
-o myapp \
.
# Calculate checksum
sha256sum myapp > myapp.sha256Question 23
How do you use build tags for feature flags?
//go:build enterprise
package features
func AdvancedAnalytics() {
// Enterprise-only feature
fmt.Println("Advanced analytics enabled")
}
//go:build !enterprise
package features
func AdvancedAnalytics() {
fmt.Println("Advanced analytics requires enterprise license")
}
// Main application
package main
func main() {
features.AdvancedAnalytics()
}
// Build commands:
// go build . // Community edition
// go build -tags enterprise . // Enterprise editionQuestion 24
How do you run benchmarks with memory allocation tracking?
func BenchmarkStringConcat(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s += "x" // Inefficient
}
}
func BenchmarkStringBuilder(b *testing.B) {
for i := 0; i < b.N; i++ {
var sb strings.Builder
for j := 0; j < 100; j++ {
sb.WriteString("x")
}
_ = sb.String()
}
}
// Command line:
// go test -bench=. -benchmem
// Output:
// BenchmarkStringConcat-8 1000000 1234 ns/op 2000 B/op 1000 allocs/op
// BenchmarkStringBuilder-8 2000000 567 ns/op 100 B/op 2 allocs/opQuestion 25
How do you build minimal Docker images?
# Dockerfile for minimal Go image
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-extldflags "-static"' -o main .
FROM scratch
COPY --from=builder /app/main /main
EXPOSE 8080
CMD ["/main"]
# Build command:
# docker build -t myapp .
# docker run -p 8080:8080 myappQuestion 26
How do you use build tags for testing different implementations?
//go:build fast
package sort
func Sort(data []int) {
// Fast but memory-intensive algorithm
// Implementation...
}
//go:build !fast
package sort
func Sort(data []int) {
// Slow but memory-efficient algorithm
// Implementation...
}
// Test file
test_test.go
func TestSort(t *testing.T) {
// Test both implementations
}
// Build and test:
// go test . // Tests slow implementation
// go test -tags fast . // Tests fast implementationQuestion 27
How do you run tests with custom timeouts?
func TestSlowOperation(t *testing.T) {
if testing.Short() {
t.Skip("Skipping slow test in short mode")
}
// Slow operation that might timeout
time.Sleep(30 * time.Second)
}
// Command line:
// go test -timeout 60s // 60 second timeout
// go test -short // Skip slow tests
// go test -timeout 10s -short // Quick test run
// Default timeout is 10 minutes for long testsQuestion 28
How do you create build tags for version-specific code?
//go:build go1.21
package main
import "fmt"
func main() {
// Uses Go 1.21+ features
fmt.Println("Using Go 1.21 features")
}
//go:build !go1.21
package main
import "fmt"
func main() {
// Compatible with older Go versions
fmt.Println("Compatible with older Go")
}
// Check Go version:
// go version
// Build automatically uses appropriate versionQuestion 29
How do you build with embedded files?
import _ "embed"
//go:embed static/*
var staticFiles embed.FS
//go:embed templates/*.html
var templates embed.FS
func main() {
data, _ := staticFiles.ReadFile("static/style.css")
fmt.Println("Embedded file size:", len(data))
}
// Build command:
// go build .
// Binary includes embedded files
// Without embedding:
// go build -ldflags "-X main.staticPath=./static" .Question 30
How do you optimize build times?
# Build optimization tips
# Use build cache
# go build -o /tmp/cache .
# Parallel builds (default)
# go build .
# Disable CGO for faster builds
# CGO_ENABLED=0 go build .
# Use go build -x to see commands
# go build -x .
# Pre-download dependencies
# go mod download
# Use go.work for multi-module workspaces
go.work
use (
./module1
./module2
)Question 31
How do you run tests with custom test main?
func TestMain(m *testing.M) {
// Setup code
db := setupDatabase()
defer db.Close()
// Run tests
code := m.Run()
// Cleanup code
cleanup()
os.Exit(code)
}
func TestDatabaseOperation(t *testing.T) {
// Test uses database set up in TestMain
}
// Command line:
// go test . // TestMain runs automatically
// TestMain is called instead of default test runnerQuestion 32
How do you create build tags for CI/CD environments?
//go:build ci
package main
import "fmt"
func main() {
fmt.Println("Running in CI environment")
// CI-specific logging, monitoring, etc.
}
//go:build !ci
package main
import "fmt"
func main() {
fmt.Println("Running in development")
// Development-specific behavior
}
// CI/CD pipeline:
# Build for CI
# go build -tags ci .
# Or set in environment:
# GOFLAGS="-tags=ci" go build .Question 33
How do you run fuzz tests?
func FuzzAdd(f *testing.F) {
f.Add(1, 2) // Seed corpus
f.Add(0, 0)
f.Add(-1, 1)
f.Fuzz(func(t *testing.T, a, b int) {
result := Add(a, b)
// Test properties
if a > 0 && b > 0 && result <= 0 {
t.Errorf("Positive + positive should be positive")
}
})
}
// Command line:
// go test -fuzz=FuzzAdd
// go test -fuzz=FuzzAdd -fuzztime=30s
// Fuzzing generates random inputs to find bugsQuestion 34
How do you build with symbol table stripping?
// Strip debug symbols for smaller binaries
// go build -ldflags "-s -w" .
// -s: Omit symbol table
// -w: Omit DWARF debug info
// Check binary size before/after
// ls -lh myapp
// For debugging builds:
// go build . // Includes debug info
// Production builds:
// go build -ldflags "-s -w" .Question 35
What is the most important consideration for Go build tooling?
