Golang Build & Run Tooling Quiz

Golang
0 Passed
0% acceptance

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.

35 Questions
~70 minutes
1

Question 1

What does the 'go build' command do?

go
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 binary
A
Compiles Go source files into an executable binary
B
Runs the Go program
C
Runs tests
D
Formats Go code
2

Question 2

How do you specify the output filename with go build?

bash
// 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 .
A
Use the -o flag: go build -o output_name .
B
Use the -out flag
C
Use the -name flag
D
Cannot specify output filename
3

Question 3

What is the difference between 'go build' and 'go run'?

go
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-123
A
go build creates a binary; go run compiles and executes without saving the binary
B
go run creates a binary; go build executes it
C
No difference
D
go build is for testing, go run is for production
4

Question 4

How do you build for a different operating system?

bash
// 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 GOARCH
A
Set GOOS and GOARCH environment variables: GOOS=target_os GOARCH=target_arch go build
B
Use -os and -arch flags
C
Use the -target flag
D
Cannot cross-compile
5

Question 5

How do you run Go tests?

go
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 ./...
A
Use go test command in the package directory
B
Use go run with test files
C
Use go build with test flag
D
Cannot run tests
6

Question 6

What are build tags and how do you use them?

go
// +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 || darwin
A
Comments that control conditional compilation: //go:build tag
B
Runtime flags
C
Package names
D
Cannot control compilation
7

Question 7

How do you run verbose tests?

bash
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:
// PASS
A
Use go test -v flag
B
Use go test --verbose
C
Use go test -log
D
Cannot run verbose tests
8

Question 8

How do you build for multiple platforms at once?

bash
#!/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"
done
A
Use shell scripts to iterate over GOOS/GOARCH combinations
B
Use go build -all flag
C
Use go build -multi flag
D
Cannot build for multiple platforms
9

Question 9

How do you run specific tests?

bash
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 test
A
Use go test -run TestName or -run "pattern"
B
Use go test -only TestName
C
Use go test -filter TestName
D
Cannot run specific tests
10

Question 10

How do you create build tags for different environments?

go
//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 build
A
Use //go:build tags and go build -tags flag
B
Use environment variables
C
Use runtime flags
D
Cannot create environment-specific builds
11

Question 11

How do you run benchmarks in Go?

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=. -benchmem
A
Use go test -bench flag with Benchmark functions
B
Use go bench command
C
Use go test -perf flag
D
Cannot run benchmarks
12

Question 12

How do you build statically linked binaries?

bash
// 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"' .
A
Use CGO_ENABLED=0 and -ldflags '-extldflags "-static"'
B
Use go build -static flag
C
Use go build -link static
D
Cannot build statically linked binaries
13

Question 13

How do you use build tags for optional features?

go
//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 support
A
Use build tags to conditionally compile optional features
B
Use runtime feature flags
C
Use environment variables
D
Cannot implement optional features
14

Question 14

How do you run tests with race detection?

bash
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
// ...
// ==================
A
Use go test -race flag
B
Use go test -detect-race
C
Use go test -concurrency
D
Cannot detect race conditions
15

Question 15

How do you build with custom ldflags?

bash
// 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)
}
A
Use -ldflags with linker flags like -X for variable injection
B
Use -flags
C
Use -linker
D
Cannot customize linking
16

Question 16

How do you run tests in parallel?

go
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)
}
A
Use t.Parallel() in tests and go test -parallel flag
B
Use go test -concurrent
C
Use go test -multi
D
Cannot run tests in parallel
17

Question 17

How do you create build tags for operating system detection?

go
//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 implementation
A
Use //go:build with GOOS values like windows, linux, darwin
B
Use runtime OS detection
C
Use environment variables
D
Cannot detect operating system at build time
18

Question 18

How do you run tests with coverage?

bash
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 statements
A
Use go test -cover and -coverprofile flags
B
Use go test -coverage
C
Use go cover command
D
Cannot measure test coverage
19

Question 19

How do you build with specific Go versions?

go
// 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)'" .
A
Use go.mod go directive and GOTOOLCHAIN environment variable
B
Use go build -version flag
C
Use go build -go flag
D
Cannot specify Go version
20

Question 20

How do you use build tags for architecture-specific code?

go
//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 version
A
Use //go:build with GOARCH values like amd64, arm64
B
Use runtime architecture detection
C
Use environment variables
D
Cannot optimize for specific architectures
21

Question 21

How do you run integration tests separately from unit tests?

go
// 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
}
A
Use build tags and separate test files for integration tests
B
Use go test -integration flag
C
Use different test functions
D
Cannot separate integration tests
22

Question 22

How do you create reproducible builds?

bash
# 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.sha256
A
Control environment variables, use consistent flags, and version pinning
B
Use random build flags
C
Use different Go versions
D
Cannot create reproducible builds
23

Question 23

How do you use build tags for feature flags?

go
//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 edition
A
Use build tags to conditionally compile feature sets
B
Use runtime feature toggles
C
Use configuration files
D
Cannot implement feature flags
24

Question 24

How do you run benchmarks with memory allocation tracking?

bash
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/op
A
Use go test -benchmem flag to show memory allocations
B
Use go test -memory
C
Use go bench -alloc
D
Cannot track memory allocations
25

Question 25

How do you build minimal Docker images?

dockerfile
# 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 myapp
A
Use multi-stage builds with scratch base image and static linking
B
Use full Ubuntu images
C
Use dynamic linking
D
Cannot create minimal Docker images
26

Question 26

How do you use build tags for testing different implementations?

go
//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 implementation
A
Use build tags to switch between different algorithm implementations
B
Use runtime switches
C
Use different packages
D
Cannot test different implementations
27

Question 27

How do you run tests with custom timeouts?

bash
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 tests
A
Use go test -timeout flag and testing.Short() for conditional tests
B
Use go test -time flag
C
Use go test -duration
D
Cannot set test timeouts
28

Question 28

How do you create build tags for version-specific code?

go
//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 version
A
Use //go:build go1.X for version-specific code
B
Use runtime version checks
C
Use environment variables
D
Cannot create version-specific code
29

Question 29

How do you build with embedded files?

go
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" .
A
Use //go:embed directives and embed.FS
B
Use go build -embed flag
C
Use external files
D
Cannot embed files
30

Question 30

How do you optimize build times?

bash
# 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
)
A
Use build cache, disable CGO, pre-download dependencies, use workspaces
B
Use slow build flags
C
Use single-threaded builds
D
Cannot optimize build times
31

Question 31

How do you run tests with custom test main?

go
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 runner
A
Implement TestMain function for custom setup and cleanup
B
Use go test -main flag
C
Use go test -setup
D
Cannot customize test execution
32

Question 32

How do you create build tags for CI/CD environments?

bash
//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 .
A
Use build tags like 'ci' for environment-specific behavior
B
Use runtime environment detection
C
Use configuration files
D
Cannot differentiate CI/CD environments
33

Question 33

How do you run fuzz tests?

go
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 bugs
A
Use FuzzXXX functions and go test -fuzz flag
B
Use go test -fuzzing
C
Use go fuzz command
D
Cannot run fuzz tests
34

Question 34

How do you build with symbol table stripping?

bash
// 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" .
A
Use -ldflags "-s -w" to strip symbols and debug info
B
Use go build -strip
C
Use go build -minimal
D
Cannot strip symbols
35

Question 35

What is the most important consideration for Go build tooling?

A
Choose appropriate tools for development vs production, understand cross-compilation, use build tags wisely, ensure reproducible builds
B
Always use default settings
C
Never use build tags
D
Only build for current platform

QUIZZES IN Golang