Go Cheat Sheet
Quick reference for Go variables, types, structs, interfaces, goroutines, channels, error handling, standard library, and module system.
Current releases: Go 1.27 and 1.26 (each release is supported until two newer ones ship). Version tags like "1.23+" below mark when a feature arrived; the go line in go.mod decides which language features a module can use.
Variables & Types
Declarations
// Variable declaration
var name string = "Alice"
var age int // Zero value: 0
var active bool // Zero value: false
// Short declaration (inside functions only)
count := 10
msg := "hello"
// Multiple declarations
var (
host = "localhost"
port = 8080
)
// Constants
const Pi = 3.14159
const (
StatusOK = 200
StatusNotOK = 400
)
// iota (auto-incrementing constants)
const (
Read = 1 << iota // 1
Write // 2
Execute // 4
)
// Pointers
p := &count // address of count
*p = 20 // write through the pointer
q := new(int) // pointer to a new zero int
r := new(int64(300)) // Go 1.26+: new() takes an initial value
// Conversions are explicit
f := float64(count)
n, err := strconv.Atoi("42") // string -> int
str := strconv.Itoa(42) // int -> string ("42"); string(42) gives "*"
// Built-ins (1.21+)
min(3, 1, 2) // 1
max(3, 1, 2) // 3
clear(m) // empty a map, or zero a slice's elements
Control Flow
if v, err := strconv.Atoi(s); err == nil { // init statement, v scoped to the if
fmt.Println(v)
}
for i := 0; i < 10; i++ {} // classic
for i := range 10 {} // 0..9 (1.22+)
for cond {} // while
for {} // forever (break / return to exit)
for i, v := range slice {} // index, value
for _, r := range "héllo" {} // iterates runes, not bytes
switch {
case x < 0:
fmt.Println("neg")
case x == 0:
fmt.Println("zero")
fallthrough // explicit; cases do NOT fall through by default
default:
fmt.Println("non-neg")
}
outer:
for _, row := range grid {
for _, cell := range row {
if cell == target {
break outer // labelled break/continue
}
}
}
Strings & Formatting
strings.Contains(s, "go")
strings.HasPrefix(s, "http")
strings.Split("a,b,c", ",") // []string{"a","b","c"}
strings.Fields(" a b ") // split on whitespace
strings.Join(parts, ", ")
strings.TrimSpace(s)
strings.ReplaceAll(s, "a", "b")
strings.EqualFold("Go", "GO") // case-insensitive equal
before, after, found := strings.Cut("k=v", "=")
var sb strings.Builder // efficient concatenation
sb.WriteString("hello")
sb.String()
fmt.Sprintf("%d %s %q %v %+v %#v %T %x %.2f %6d", ...)
// %v value, %+v with field names, %#v Go syntax, %T type, %q quoted, %w (Errorf only) wrapped error
Basic Types
| Type | Zero Value | Example |
|---|---|---|
bool | false | true |
string | "" | "hello" |
int, int8/16/32/64 | 0 | 42 |
uint, uint8/16/32/64 | 0 | 42 |
float32, float64 | 0.0 | 3.14 |
complex64, complex128 | (0+0i) | 1+2i |
byte (alias uint8) | 0 | 'A' |
rune (alias int32) | 0 | 'Z' |
Slices & Arrays
// Array (fixed length)
arr := [3]int{1, 2, 3}
// Slice (dynamic length)
s := []int{1, 2, 3}
s = append(s, 4, 5) // Append elements
s2 := make([]int, 5) // Length 5, cap 5
s3 := make([]int, 0, 10) // Length 0, cap 10
// Slice operations
sub := s[1:3] // Elements at index 1, 2
len(s) // Length
cap(s) // Capacity
copy(dst, src) // Copy elements
// Delete element at index i
s = append(s[:i], s[i+1:]...)
s = slices.Delete(s, i, i+1) // same, and zeroes the freed tail (1.22+)
// Slices package (1.21+)
import "slices"
slices.Sort(s)
slices.Contains(s, 3)
idx := slices.Index(s, 3)
slices.SortFunc(users, func(a, b User) int { return cmp.Compare(a.Age, b.Age) })
slices.SortStableFunc(users, func(a, b User) int { return strings.Compare(a.Name, b.Name) })
i, found := slices.BinarySearch(sorted, 3)
slices.Max(s) // panics on empty slice
slices.Reverse(s)
slices.Equal(a, b)
slices.Compact(s) // drop consecutive duplicates (sort first to dedupe)
slices.Insert(s, i, 10, 11)
s2 := slices.Clone(s)
slices.IndexFunc(users, func(u User) bool { return u.ID == 7 })
slices.Chunk(s, 100) // iterator over sub-slices of up to 100 (1.23+)
Slicing shares the underlying array: sub := s[1:3] then sub[0] = 9 also changes s[1], and append(sub, x) can overwrite s[3]. Use slices.Clone or a full slice expression s[1:3:3] to cut the link.
Maps
// Create map
m := map[string]int{
"alice": 90,
"bob": 85,
}
m2 := make(map[string]int)
// Operations
m["charlie"] = 92 // Set
val := m["alice"] // Get (zero value if missing)
val, ok := m["dave"] // Check existence
delete(m, "bob") // Delete key
len(m) // Number of keys
// Iterate
for key, val := range m {
fmt.Println(key, val)
}
// Maps package (1.21+). Keys/Values (1.23+) return iterators, not slices.
import "maps"
for k := range maps.Keys(m) { fmt.Println(k) }
keys := slices.Sorted(maps.Keys(m)) // sorted []string
vals := slices.Collect(maps.Values(m)) // []int
m3 := maps.Clone(m)
maps.Copy(dst, src) // dst[k] = v for every k in src
maps.DeleteFunc(m, func(k string, v int) bool { return v < 50 })
Map iteration order is random by design. Sort the keys when you need stable output.
Iterators (range over func, 1.23+)
import "iter"
// iter.Seq[V] is func(yield func(V) bool); iter.Seq2[K, V] yields pairs
func Count(n int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := range n {
if !yield(i) { // consumer broke out of the loop
return
}
}
}
}
for x := range Count(3) { fmt.Println(x) }
// Std-lib iterators
for i, v := range slices.All(s) {} // index, value
for v := range slices.Values(s) {}
for line := range strings.Lines(text) {} // 1.24+, keeps the "\n"
for part := range strings.SplitSeq(s, ",") {} // 1.24+, no intermediate slice
Generics (1.18+)
// Type parameter with a constraint
func Map[T, U any](xs []T, f func(T) U) []U {
out := make([]U, 0, len(xs))
for _, x := range xs {
out = append(out, f(x))
}
return out
}
// Constraint interfaces: ~T means "T or any type whose underlying type is T"
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
// Generic types
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
v := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v, true
}
// Usage: type arguments are usually inferred
Sum([]float64{1.5, 2}) // 3.5
var st Stack[string]
| Constraint | Allows |
|---|---|
any | Any type |
comparable | Types usable with == (map keys) |
cmp.Ordered | Types usable with < (ints, floats, strings) |
~string | string and named types based on it |
Methods cannot have their own type parameters; only functions and types can.
Structs & Interfaces
Structs
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
}
// Create
u := User{ID: 1, Name: "Alice"}
u2 := &User{Name: "Bob"} // Pointer to struct
// Methods (value receiver)
func (u User) FullName() string {
return u.Name
}
// Methods (pointer receiver - can modify)
func (u *User) SetName(name string) {
u.Name = name
}
// Embedding (composition)
type Admin struct {
User // Embeds all User fields/methods
Level int
}
a := Admin{User: User{Name: "Root"}, Level: 1}
a.Name // Access embedded field directly
// Anonymous struct (tests, one-off JSON)
point := struct{ X, Y int }{1, 2}
// Compile-time check that a type implements an interface
var _ io.Reader = (*MyReader)(nil)
Interfaces
// Interface definition
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
// Composed interface
type ReadWriter interface {
Reader
Writer
}
// Implicit implementation (no "implements" keyword)
type MyReader struct{}
func (r MyReader) Read(p []byte) (int, error) {
return 0, nil
}
// MyReader now satisfies Reader interface
// Empty interface (any value)
var x any // same as interface{}
// Type assertion
val, ok := x.(string)
// Type switch
switch v := x.(type) {
case string:
fmt.Println("string:", v)
case int:
fmt.Println("int:", v)
default:
fmt.Println("unknown")
}
Goroutines & Channels
Goroutines
// Launch goroutine
go func() {
fmt.Println("running concurrently")
}()
// WaitGroup for synchronization
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
doWork(id)
}(i)
}
wg.Wait()
// Same thing with WaitGroup.Go (1.25+): Add/Done handled for you
for i := range 5 {
wg.Go(func() { doWork(i) }) // i is per-iteration since 1.22
}
wg.Wait()
// errgroup (golang.org/x/sync/errgroup): first error cancels the rest
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10) // at most 10 goroutines at once
for _, url := range urls {
g.Go(func() error { return fetch(ctx, url) })
}
if err := g.Wait(); err != nil {
return err
}
Channels
// Unbuffered channel (blocks until both sides ready)
ch := make(chan string)
// Buffered channel
ch := make(chan int, 100)
// Send and receive
ch <- "hello" // Send
msg := <-ch // Receive
// Directional channels (function signatures)
func producer(out chan<- int) {} // Send only
func consumer(in <-chan int) {} // Receive only
// Close channel
close(ch)
// Range over channel (until closed)
for val := range ch {
fmt.Println(val)
}
// Detect a closed channel
v, ok := <-ch // ok == false once closed and drained
| Operation | nil channel | closed channel |
|---|---|---|
| Send | Blocks forever | Panics |
| Receive | Blocks forever | Returns zero value, ok == false |
| Close | Panics | Panics |
Only the sender should close a channel, and only when receivers need to know no more values are coming.
Select
select {
case msg := <-ch1:
fmt.Println("from ch1:", msg)
case msg := <-ch2:
fmt.Println("from ch2:", msg)
case ch3 <- "outgoing":
fmt.Println("sent to ch3")
case <-time.After(5 * time.Second):
fmt.Println("timeout")
default:
fmt.Println("no channel ready")
}
Common Concurrency Patterns
// Fan-out / fan-in
func fanOut(in <-chan int, workers int) []<-chan int {
outs := make([]<-chan int, workers)
for i := 0; i < workers; i++ {
outs[i] = worker(in)
}
return outs
}
// Worker pool
func workerPool(jobs <-chan Job, results chan<- Result, n int) {
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
results <- process(job)
}
}()
}
go func() {
wg.Wait()
close(results)
}()
}
// Rate limiter
limiter := time.NewTicker(100 * time.Millisecond)
defer limiter.Stop()
for req := range requests {
<-limiter.C
go handle(req)
}
Error Handling
Basic Patterns
// Return error
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Check error
result, err := divide(10, 0)
if err != nil {
log.Fatal(err)
}
// Wrap errors (add context)
if err != nil {
return fmt.Errorf("processing user %d: %w", id, err)
}
// Unwrap errors
if errors.Is(err, os.ErrNotExist) {
// Handle file not found
}
// Check error type
var pathErr *os.PathError
if errors.As(err, &pathErr) {
fmt.Println("path:", pathErr.Path)
}
// Generic version, no target variable needed (1.26+)
if pathErr, ok := errors.AsType[*os.PathError](err); ok {
fmt.Println("path:", pathErr.Path)
}
// Combine several errors (1.20+); errors.Is/As check every one
err := errors.Join(err1, err2) // nil if all are nil
errs = append(errs, validate(x)) // collect...
return errors.Join(errs...) // ...and return them together
// Wrap more than one error at once (1.20+)
fmt.Errorf("save %s: %w (cleanup: %w)", name, err, cleanupErr)
Custom Errors
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation: %s - %s", e.Field, e.Message)
}
// Sentinel errors
var (
ErrNotFound = errors.New("not found")
ErrUnauthorized = errors.New("unauthorized")
)
Defer, Panic, Recover
// Defer (LIFO order, runs on function exit)
func readFile(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
}
// Recover from panic
func safeHandler() {
defer func() {
if r := recover(); r != nil {
log.Printf("recovered: %v", r)
}
}()
riskyOperation()
}
// Deferred call arguments are evaluated immediately, the call runs later
for i := range 3 {
defer fmt.Println(i) // prints 2, 1, 0
}
// Capture a Close error with a named return
func write(path string) (err error) {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() { err = errors.Join(err, f.Close()) }()
_, err = f.WriteString("data")
return err
}
Common Standard Library
net/http
// Simple HTTP server
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
mux.HandleFunc("GET /users/{id}", getUser) // method + wildcard patterns (1.22+)
http.ListenAndServe(":8080", mux)
// Read the wildcard in the handler
func getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
q := r.URL.Query().Get("expand") // ?expand=...
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"id": id, "expand": q})
}
// Production server: set timeouts (the zero-value server has none)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
go srv.ListenAndServe()
// on SIGTERM:
srv.Shutdown(ctx) // stop accepting, finish in-flight requests
// Middleware is just a func(http.Handler) http.Handler
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
slog.Info("request", "method", r.Method, "path", r.URL.Path, "dur", time.Since(start))
})
}
// HTTP client
resp, err := http.Get("https://api.example.com/data")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Client with timeout
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(url)
// A 404 or 500 is NOT an error from Do/Get: check the status yourself
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status %s", resp.Status)
}
http.DefaultClient and http.Get have no timeout. Always use a client with Timeout or a request context with a deadline, and always close resp.Body (otherwise the connection is not reused).
encoding/json
// Struct to JSON
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Age int `json:"age"`
}
data, err := json.Marshal(user)
json.NewEncoder(w).Encode(user) // Write to io.Writer
// JSON to struct
var u User
err := json.Unmarshal(data, &u)
json.NewDecoder(r.Body).Decode(&u) // Read from io.Reader
// Dynamic JSON
var result map[string]any
json.Unmarshal(data, &result)
| Tag | Effect |
|---|---|
json:"name" | Field name in JSON |
json:"-" | Never encode/decode this field |
json:"name,omitempty" | Skip if false, 0, "", nil, or empty slice/map (does not skip zero structs or time.Time) |
json:"name,omitzero" | Skip if the zero value, including zero structs and time.Time, or if IsZero() returns true (1.24+) |
json:"id,string" | Encode a number/bool as a JSON string |
Only exported (capitalised) fields are encoded. Numbers in map[string]any decode as float64; use dec.UseNumber() to keep precision. dec.DisallowUnknownFields() rejects unexpected keys.
log/slog (structured logging, 1.21+)
import "log/slog"
slog.Info("user created", "id", 42, "email", email) // key-value pairs
slog.Error("db failed", "err", err)
// JSON output, minimum level Debug, set as the default logger
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
slog.SetDefault(logger)
// Typed attributes (no allocations for the key-value parsing) and groups
logger.Info("req", slog.Int("status", 200), slog.Duration("dur", d),
slog.Group("user", slog.String("id", uid)))
// Child logger with fixed fields
reqLog := logger.With("request_id", rid)
reqLog.Warn("slow query", "ms", 950)
// Pass ctx so handlers can pull trace IDs
logger.InfoContext(ctx, "done")
time
now := time.Now()
d := 1500 * time.Millisecond
time.Since(start) // elapsed Duration
deadline := now.Add(24 * time.Hour)
t, err := time.Parse(time.RFC3339, "2026-11-09T10:00:00Z")
now.Format("2006-01-02 15:04:05") // layout uses the reference time Mon Jan 2 15:04:05 MST 2006
time.ParseDuration("1h30m")
os, io and files
data, err := os.ReadFile("config.json")
err = os.WriteFile("out.txt", data, 0o644)
os.MkdirAll("a/b/c", 0o755)
os.Getenv("HOME")
v, ok := os.LookupEnv("PORT") // distinguish unset from empty
f, _ := os.Open("big.log")
sc := bufio.NewScanner(f) // line by line; default max line is 64 KiB (sc.Buffer to raise)
for sc.Scan() {
fmt.Println(sc.Text())
}
// Embed files into the binary
import "embed"
//go:embed static/*
var static embed.FS
Graceful shutdown on signals
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
<-ctx.Done() // blocks until Ctrl+C or SIGTERM
context
// Context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Context with cancel
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Pass context to functions
func fetchData(ctx context.Context, url string) error {
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)
// ...
}
// Check cancellation
select {
case <-ctx.Done():
return ctx.Err() // context.Canceled or DeadlineExceeded
case result := <-ch:
return process(result)
}
// Cancel with a reason (1.20+)
ctx, cancel := context.WithCancelCause(parent)
cancel(errors.New("upstream gone"))
context.Cause(ctx) // "upstream gone"
// Keep values but drop the parent's cancellation (background work after a request, 1.21+)
bg := context.WithoutCancel(r.Context())
// Request-scoped values: use an unexported key type to avoid collisions
type ctxKey struct{}
ctx = context.WithValue(ctx, ctxKey{}, userID)
uid, _ := ctx.Value(ctxKey{}).(string)
context.Context is always the first parameter, named ctx. Don't store it in structs, and don't pass nil (use context.TODO()).
sync
// Mutex
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
// critical section
// RWMutex (multiple readers, single writer)
var rw sync.RWMutex
rw.RLock() // Read lock (shared)
rw.RUnlock()
rw.Lock() // Write lock (exclusive)
rw.Unlock()
// Once (run exactly once)
var once sync.Once
once.Do(func() {
initExpensiveResource()
})
// sync.Map (concurrent-safe map)
var m sync.Map
m.Store("key", "value")
val, ok := m.Load("key")
m.Delete("key")
// Lazily computed values (1.21+)
getConfig := sync.OnceValue(func() *Config { return loadConfig() })
cfg := getConfig() // loadConfig runs on the first call only
// Atomics for counters and flags
var hits atomic.Int64 // sync/atomic
hits.Add(1)
hits.Load()
Never copy a sync.Mutex, WaitGroup or Once after first use (pass pointers, use pointer receivers). go vet catches most copies.
Module System
Module Commands
| Command | Description |
|---|---|
go mod init module/path | Initialize new module |
go mod tidy | Add missing, remove unused deps |
go mod download | Download dependencies |
go mod vendor | Copy deps to vendor directory |
go mod graph | Print dependency graph |
go get pkg@version | Add or update dependency |
go get pkg@latest | Update to latest version |
go get -u ./... | Update all direct and indirect deps (minor/patch) |
go get pkg@none | Remove a dependency |
go get go@1.27 | Raise the module's go version |
go get -tool golang.org/x/tools/cmd/stringer | Track a dev tool in go.mod (1.24+); run with go tool stringer |
go list -m all | List all dependencies |
go list -m -u all | List deps with available updates |
go mod why -m pkg | Why is this module needed? |
go mod edit -replace example.com/lib=../lib | Use a local copy of a dependency |
go work init ./api ./lib | Multi-module workspace (go.work, keep it out of git usually) |
go env GOPATH GOPROXY GOPRIVATE | Show Go environment |
go env -w GOPRIVATE=github.com/myorg/* | Fetch private modules directly, skip proxy/checksum DB |
go version -m ./app | Show module versions baked into a binary |
go.mod has a go 1.N line (minimum language version) and optionally a toolchain line. If your installed Go is older, the go command downloads the required toolchain automatically (GOTOOLCHAIN=local disables that).
Code Quality
| Command | Description |
|---|---|
gofmt -w . / go fmt ./... | Format code |
go vet ./... | Static checks (printf args, lock copies, unreachable code...) |
go fix ./... | Apply modernizers (rewrite code to newer idioms; revamped in 1.26) |
govulncheck ./... | Known vulnerabilities that your code actually reaches (golang.org/x/vuln/cmd/govulncheck) |
staticcheck ./... / golangci-lint run | Popular third-party linters |
go doc fmt.Printf | Docs in the terminal |
go generate ./... | Run //go:generate directives |
Build & Run
| Command | Description |
|---|---|
go run . | Compile and run |
go build -o app . | Compile binary |
go build -ldflags="-s -w" . | Smaller binary (strip debug) |
go install . | Install to $GOPATH/bin |
CGO_ENABLED=0 go build . | Static binary (no cgo) |
GOOS=linux GOARCH=amd64 go build . | Cross-compile |
go build -ldflags="-X main.version=1.2.3" . | Inject a value into a string variable at build time |
go build -trimpath . | Strip local file paths (reproducible builds) |
go build -race . | Binary with the race detector |
go build -tags integration . | Include files with //go:build integration |
go install golang.org/x/tools/gopls@latest | Install a tool binary into $GOBIN (default $GOPATH/bin) |
go tool dist list | All supported GOOS/GOARCH pairs |
Testing
// Basic test (file: xxx_test.go)
func TestAdd(t *testing.T) {
got := Add(2, 3)
if got != 5 {
t.Errorf("Add(2,3) = %d, want 5", got)
}
}
// Table-driven tests
func TestDivide(t *testing.T) {
tests := []struct {
name string
a, b float64
want float64
wantErr bool
}{
{"normal", 10, 2, 5, false},
{"zero", 10, 0, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Divide(tt.a, tt.b)
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("got %v, want %v", got, tt.want)
}
})
}
}
// Benchmark
func BenchmarkSort(b *testing.B) {
for i := 0; i < b.N; i++ {
sort.Ints(generateData())
}
}
// Benchmark with b.Loop (1.24+): setup outside the loop isn't timed,
// and the compiler can't optimise the body away
func BenchmarkSortLoop(b *testing.B) {
data := generateData()
for b.Loop() {
slices.Sort(slices.Clone(data))
}
}
// Helpers
func TestThing(t *testing.T) {
t.Setenv("APP_ENV", "test") // restored after the test (panics if combined with t.Parallel)
dir := t.TempDir() // removed automatically
ctx := t.Context() // cancelled when the test ends (1.24+)
t.Cleanup(func() { /* teardown */ })
_ = dir; _ = ctx
}
func TestIndependent(t *testing.T) {
t.Parallel() // run alongside other parallel tests
}
// Fuzz test (go test -fuzz=FuzzParse)
func FuzzParse(f *testing.F) {
f.Add("seed input")
f.Fuzz(func(t *testing.T, s string) {
Parse(s) // must not panic
})
}
// Example test: output is checked, and it shows up in go doc
func ExampleAdd() {
fmt.Println(Add(1, 2))
// Output: 3
}
testing/synctest (1.25+) runs concurrent code in a bubble with a fake clock, so tests of timeouts and tickers finish instantly and deterministically. net/http/httptest gives you httptest.NewRecorder() and httptest.NewServer(handler) for HTTP tests.
Test Commands
| Command | Description |
|---|---|
go test ./... | Run all tests |
go test -v ./... | Verbose output |
go test -run TestName ./pkg | Run specific test |
go test -count=1 ./... | Disable test caching |
go test -race ./... | Race condition detector |
go test -cover ./... | Show coverage percentage |
go test -coverprofile=cover.out | Generate coverage file |
go tool cover -html=cover.out | View coverage in browser |
go test -bench=. ./... | Run benchmarks |
go test -benchmem ./... | Benchmark with memory stats |
go test -run '^TestDivide$/zero' ./pkg | Run one subtest (regex per level) |
go test -short ./... | Skip tests that check testing.Short() |
go test -fuzz=FuzzParse -fuzztime=30s | Fuzz for 30 seconds |
go test -cpuprofile cpu.out -bench . | CPU profile; inspect with go tool pprof cpu.out |
go test -failfast ./... | Stop at the first failure |
go test -timeout 30s ./... | Fail tests that run longer (default 10m) |
When to Use X vs Y
| Decision | Choice A | Choice B | Use A When | Use B When |
|---|---|---|---|---|
| Data | Slice | Array | Dynamic size (almost always) | Fixed size, value semantics |
| Receiver | Value (t T) | Pointer (t *T) | Small, immutable | Large struct, needs mutation |
| Concurrency | Channel | Mutex | Communicating data between goroutines | Protecting shared state |
| Error | Sentinel var Err | Custom type | Simple identity check | Need extra context/fields |
| Interface | Small (1-2 methods) | Large | Composability, flexibility | Only when genuinely needed |
| String building | strings.Builder | + concat | Loop, many parts | 2-3 parts, simple concat |
| JSON | Struct tags | map[string]any | Known schema | Dynamic / unknown schema |
Test Yourself
-
What is the zero value of a
stringin Go?""(empty string) -
How do you check if a key exists in a map?
val, ok := m["key"]-- check theokboolean. -
What keyword launches a function as a goroutine?
go -
How do you create a buffered channel of capacity 100?
ch := make(chan int, 100) -
What function synchronizes goroutines to wait for all to finish?
sync.WaitGroupwithAdd,Done, andWait. -
How do you wrap an error with context in Go?
fmt.Errorf("processing user %d: %w", id, err) -
What does
deferdo? Schedules a function call to run when the enclosing function exits (LIFO order). -
How do you cross-compile a Go binary for Linux amd64?
GOOS=linux GOARCH=amd64 go build . -
What command runs the race condition detector?
go test -race ./... -
What is the difference between a value receiver and a pointer receiver? Value receivers
(t T)work on a copy; pointer receivers(t *T)can modify the original and avoid copying large structs.
Common Gotchas
- Goroutine leaks. If a goroutine blocks on a channel that is never closed or read, it leaks forever. Always ensure channels are eventually closed or read.
- Loop variable capture in goroutines. Before Go 1.22,
go func() { use(i) }()captures the same variable. Pass it as a parameter:go func(i int) { use(i) }(i). - Nil map writes panic. Reading from a nil map returns the zero value, but writing to one panics. Always initialize with
make(map[K]V). - Ignoring errors.
result, _ := doSomething()silently discards errors. Always checkerr != nilin production code. - A nil pointer in an interface is not a nil interface.
var p *MyErr = nil; var err error = p; err != nilistrue. Return a literalnil, not a typed nil pointer. :=shadows outer variables.x, err := f()inside anif/forblock creates newxanderr, leaving the outer ones untouched.appendmay or may not copy. It reuses the backing array while capacity lasts, so two slices from the same base can overwrite each other. Always use the result:s = append(s, x).deferin a loop runs at function exit, not per iteration. Opening files in a loop withdefer f.Close()keeps them all open. Move the body into a function.time.Afterin a long-runningselectloop allocates a timer every iteration. Before 1.23 those timers weren't collected until they fired; reuse atime.NewTimer(orReset) in hot loops.for i, v := rangecopiesv. Modifyingvdoesn't change the slice element; uses[i].Field = ....- Strings are bytes.
len("héllo")is 6 ands[1]is a byte. Use[]rune(s)orrange s/utf8.RuneCountInStringfor characters.
One-Liner Summary
Go is a compiled, statically typed language built for simplicity and concurrency -- goroutines and channels make it trivial to write fast, concurrent network services.