Go

Build Tags + Conditional Compilation

admin by @admin ADMIN
5m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`//go:build` constraints control which files compile under which conditions — different code for Linux vs Windows, dev vs prod, with/without a feature. Standard library uses this heavily.
Go
Raw
// File: storage_linux.go
//go:build linux

package storage

import "syscall"

func DiskFree(path string) (uint64, error) {
    var stat syscall.Statfs_t
    if err := syscall.Statfs(path, &stat); err != nil {
        return 0, err
    }
    return stat.Bavail * uint64(stat.Bsize), nil
}

// File: storage_windows.go
//go:build windows

package storage

import "golang.org/x/sys/windows"

func DiskFree(path string) (uint64, error) {
    var free, total, totalFree uint64
    p, _ := windows.UTF16PtrFromString(path)
    err := windows.GetDiskFreeSpaceEx(p, &free, &total, &totalFree)
    return free, err
}

// File: feature_pro.go
//go:build pro              // built only with: go build -tags=pro

package feature

func PremiumFeature() string { return "premium enabled" }

// Tag combinations:
//go:build linux && amd64   // AND
//go:build linux || darwin  // OR
//go:build !windows         // NOT
//
// Build: go build -tags="pro debug" ./...
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.