Contents

Go (Golang) Cheat Sheet

Snippets for everyday Go, from slices and maps to goroutines, generics and net/http. Each example was compiled and run with Go 1.27.4, and the output under it is what it printed. Features newer than Go 1.21 say which release added them.

By Bogdan SanduUpdated November 18, 2026Tested on Go 1.27.4

Check Go code

Ctrl+Enter lints. Check Printf verbs matches every verb with its argument, like go vet. JSON to Go struct writes types with json tags. Time layout turns %Y-%m-%d, yyyy-MM-dd or an example date such as Tue, 29 Sep 2026 14:05:09 GMT into a Go layout and explains any Go layout. Regex for Go flags what RE2 cannot do and writes the regexp.MustCompile call. Run on godbolt opens the program in Compiler Explorer in a new tab; nothing is sent until you press it.
Output

          
Paste Go code, a Printf call, JSON, a struct, a date format, a regex or a go.mod above, then pick an action.

Command builders

Command

          

Install, Run & Build

Install Go

macOS with Homebrew, or the official tarball on Linux

macOS / Linux

Remove the old /usr/local/go before unpacking: extracting on top of an older release leaves stale files that break builds. $HOME/go/bin is where go install puts tools.

brew install go

curl -LO https://go.dev/dl/go1.27.4.linux-amd64.tar.gz

sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.27.4.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin
go version// Output:
// go version go1.27.4 linux/amd64

Windows with winget, or the MSI installer from go.dev/dl

Windows

The installer adds Go and %USERPROFILE%\go\bin to PATH; open a new terminal afterwards so it sees the change.

winget install GoLang.Go
go version
go env GOPATH// Output:
// go version go1.27.4 windows/amd64
// C:\Users\you\go

No install at all: run the official image

Docker

The golang image tags follow the releases: golang:1.27 is the latest 1.27.x, golang:1.27.4 pins the patch release, and -alpine variants are smaller.

docker run --rm -v "$PWD":/src -w /src golang:1.27 go run .
docker run --rm -v "$PWD":/src -w /src golang:1.27 go test ./...

Hello, World

A module, a main package and a main function

Every executable is package main with a func main, which takes no arguments and returns nothing. os.Args has the command line and os.Exit(1) sets the exit code.

package main

import "fmt"

func main() {
    fmt.Println("Hello, Gopher")
}// Output:
// Hello, Gopher

The commands around it

go mod init writes go.mod, which names the module and the Go version. go run compiles to a temporary directory and runs; go build writes a binary you can copy to any machine with the same OS and CPU, no runtime needed.

mkdir hello && cd hello
go mod init example.com/hello
go run .
go build -o hello .
./hello// Output:
// go: creating new go.mod: module example.com/hello
// Hello, Gopher
// Hello, Gopher

go run, build, install

The everyday commands

./... means this directory and everything below it. Build results are cached in $(go env GOCACHE), so a second build of unchanged code is almost instant.

go run .                      # compile and run the package in this directory

go run ./cmd/server -port 8080  # arguments after the package go to the program

go build ./...                # compile every package as a check, write no binaries

go build -o bin/app ./cmd/app # choose the output file

go install ./cmd/app          # build and copy to $(go env GOPATH)/bin

go install golang.org/x/tools/gopls@latest   # install a tool from a module

go vet ./...                  # static checks the compiler skips

go fmt ./...                  # format every file (gofmt -l -w)

go env: where things live

go env -w writes to the per-user config file shown by go env GOENV, so the setting sticks for every terminal. Environment variables still win over it.

go env GOPATH GOROOT GOMODCACHE GOCACHE
go env GOOS GOARCH CGO_ENABLED
go env -w GOPRIVATE=github.com/acme/*
go env -u GOPRIVATE

Toolchains

The go line picks the toolchain

Go 1.21+

Since Go 1.21 the go command downloads the toolchain that go.mod asks for when yours is older, so everyone on the team builds with the same release. GOTOOLCHAIN=local turns that off.

go version                      # the toolchain you are running

go get go@1.27.1                # require at least Go 1.27.1 for this module

go get toolchain@go1.27.1       # prefer this toolchain for this module

GOTOOLCHAIN=local go build ./...  # never download, use the installed Go

GOTOOLCHAIN=go1.26.8 go version   # run a specific release once// Output:
// go version go1.27.1 linux/amd64

A second Go version side by side

The golang.org/dl wrappers install any release next to your main one, handy for checking that code still builds on the oldest version you support.

go install golang.org/dl/go1.26.8@latest
go1.26.8 download
go1.26.8 test ./...

Packages & Imports

Packages and Imports

One package per directory

The package name is the last element of the import path by convention. Standard library imports come first, then your own and third-party ones, separated by a blank line; goimports sorts them for you.

package inventory

import (
    "fmt"
    "strings"

    "example.com/shop/internal/money"
    "github.com/google/go-cmp/cmp"
)

Alias, blank and dot imports

A blank import registers something, such as a database driver or an image format, through the package's init function. Dot imports hide where names come from; keep them out of normal code.

import (
    mrand "math/rand/v2"            // alias: rename to avoid a clash

    _ "github.com/lib/pq"           // blank: run the package's init only

    _ "embed"                       // needed for //go:embed

    . "github.com/onsi/gomega"      // dot: use names without a prefix, tests only

)

Capital letter means exported

Go has no public or private keywords. An identifier starting with an upper case letter is visible outside its package; everything else is private to the package, not to the type.

package money

type Amount struct {
    Cents    int64  // exported: other packages can use it

    currency string // unexported: only package money sees it

}

func New(cents int64) Amount { return Amount{Cents: cents, currency: "USD"} }
func round(x float64) int64   { return int64(x + 0.5) }

init and Program Start

Package variables, then init, then main

Imported packages initialize first, then this package's variables in dependency order, then its init functions in source order. A file may have several init functions; none can be called by name.

package main

import "fmt"

var ready = setup()

func setup() bool {
    fmt.Println("1. package variables")
    return true
}

func init() {
    fmt.Println("2. init, ready =", ready)
}

func main() {
    fmt.Println("3. main")
}// Output:
// 1. package variables
// 2. init, ready = true
// 3. main

Project Layout

A common layout for an application module

Go does not require any layout. The one rule the go command enforces is internal/: packages under it can only be imported by code rooted at internal's parent. Start flat and add directories when the code asks for them.

shop/
    go.mod                 module example.com/shop
    cmd/
        api/main.go        package main: one directory per binary
        worker/main.go
    internal/
        orders/orders.go   importable only inside example.com/shop
        money/money.go
    web/static/            files embedded with //go:embed

Doc comments and go doc

A comment directly above a declaration, starting with its name, is its documentation, shown by go doc and pkg.go.dev. go doc accepts package@version since Go 1.27.

// Package money handles amounts in integer cents.

package money

// Add returns the sum of a and b. It panics if the currencies differ.

func Add(a, b Amount) Amount { return Amount{Cents: a.Cents + b.Cents, currency: a.currency} }

go doc example.com/shop/internal/money Add
go doc -all strings
go doc golang.org/x/sync/errgroup@v0.23.0 Group

Built-in Functions

The functions every package can use without an import

Go 1.21+

The built-ins are append, cap, clear, close, complex, copy, delete, imag, len, make, max, min, new, panic, print, println, real and recover. min, max and clear arrived in Go 1.21; len of a string counts bytes.

s := make([]int, 2, 5)
s = append(s, 7)
dst := make([]int, 2)
n := copy(dst, s)
m := map[string]int{"a": 1, "b": 2}
delete(m, "a")
fmt.Println(len(s), cap(s), n, dst, len(m))
fmt.Println(min(3, 1, 2), max(2.5, 1), min("pear", "apple"))
c := complex(1, 2)
fmt.Println(real(c), imag(c))
clear(m)
fmt.Println(len(m), len("héllo"))// Output:
// 3 5 2 [0 0] 1
// 1 2.5 apple
// 1 2
// 0 6

Variables & Constants

Declaring Variables

var, :=, and several at once

:= declares and assigns, only inside functions, and at least one name on the left must be new. var works everywhere and is how you declare without a value. x, y = y, x swaps without a temporary.

var name string = "gopher"
var count int
age := 14
x, y := 1, 2
x, y = y, x
var (
    host = "localhost"
    port = 8080
)
fmt.Println(name, count, age, x, y, host, port)// Output:
// gopher 0 14 2 1 localhost 8080

Zero values: nothing is ever uninitialized

Every variable starts at its type's zero value: 0, false, "", or nil for pointers, slices, maps, channels, functions and interfaces. A nil slice or map can be read and ranged over; only writing to a nil map panics.

var i int
var f float64
var b bool
var s string
var p *int
var sl []int
var m map[string]int
var err error
fmt.Printf("%v %v %v %q %v %v %v %v\n", i, f, b, s, p, sl, m, err)
fmt.Println(sl == nil, m == nil, len(sl), len(m))// Output:
// 0 0 false "" <nil> [] map[] <nil>
// true true 0 0

Shadowing with := in an inner scope

:= inside a block declares a new variable that hides the outer one. The classic bug is err := inside an if or for, which leaves the outer err unchanged; = assigns to the existing one.

x := 1
if true {
    x := 2
    x++
    fmt.Println("inner", x)
}
fmt.Println("outer", x)// Output:
// inner 3
// outer 1

The blank identifier

_ discards a value you do not need. var _ Interface = (*T)(nil) is a compile time check that T implements Interface, with no cost at run time.

_, err := strconv.Atoi("42")
for _, v := range []string{"a", "b"} {
    fmt.Print(v)
}
var _ fmt.Stringer = (*strings.Builder)(nil)
fmt.Println("", err)// Output:
// ab <nil>

Constants and iota

iota numbers constants in a block

iota starts at 0 in each const block and grows by one per line; a line without an expression repeats the previous one. That gives enums, bit flags and unit sizes in a few lines.

package main

import "fmt"

type Weekday int

const (
    Sunday Weekday = iota
    Monday
    Tuesday
)

const (
    _  = iota
    KB = 1 << (10 * iota)
    MB
    GB
)

type Perm uint8

const (
    Read Perm = 1 << iota
    Write
    Exec
)

func main() {
    fmt.Println(Sunday, Monday, Tuesday)
    fmt.Println(KB, MB, GB)
    fmt.Printf("%03b %03b %03b %03b\n", Read, Write, Exec, Read|Exec)
}// Output:
// 0 1 2
// 1024 1048576 1073741824
// 001 010 100 101

Untyped constants have arbitrary precision

Constants are exact at compile time and only need to fit when they are used. An untyped constant takes the type its context wants, which is why time.Second * 2 and 1.5 * math.Pi both work.

const huge = 1 << 100
const small = huge >> 98
var f float64 = huge
fmt.Println(small, f)
const c = 'A' + 1
fmt.Printf("%c %T\n", c, c)// Output:
// 4 1.2676506002282294e+30
// B int32

new with a Value

Go 1.26+

new(expr) allocates and initializes in one step

Go 1.26+

Before Go 1.26 an optional pointer field needed a helper such as func ptr[T any](v T) *T or a temporary variable. new(expr) returns a pointer to a new variable holding the value.

package main

import "fmt"

type Profile struct {
    Name string
    Age  *int
}

func main() {
    p := Profile{Name: "ann", Age: new(36)}
    q := new("hello")
    fmt.Println(*p.Age, *q)
}// Output:
// 36 hello

Types & Conversions

Basic Types

The built-in types

TypeSizeNotes
bool1 bytetrue or false
int, uint8 bytes on 64-bitthe default integer type; 4 bytes on 32-bit targets
int8 to int641 to 8 bytessigned, exact width
uint8 to uint641 to 8 bytesunsigned, exact width
byte1 bytealias for uint8
rune4 bytesalias for int32, one Unicode code point
uintptrpointer sizeinteger that can hold an address, for unsafe code
float32, float644, 8 bytesIEEE 754; float64 is the default
complex64, complex1288, 16 bytescomplex numbers
string16 bytes headerimmutable bytes, usually UTF-8

Sizes and limits

math.MaxInt and math.MinInt match the size of int on the target. unsafe.Sizeof shows a string is two words (pointer, length) and a slice three (pointer, length, capacity).

fmt.Println(math.MaxInt64, math.MinInt64)
fmt.Println(math.MaxUint32, math.MaxInt8)
fmt.Println(math.MaxFloat64, math.SmallestNonzeroFloat64)
fmt.Println(unsafe.Sizeof(int(0)), unsafe.Sizeof(""), unsafe.Sizeof([]int{}))// Output:
// 9223372036854775807 -9223372036854775808
// 4294967295 127
// 1.7976931348623157e+308 5e-324
// 8 16 24

Conversions

Conversions are always explicit

Go never converts numbers implicitly, not even int to int64. Converting to a smaller integer keeps the low bits, and float to int truncates toward zero. Converting a constant that does not fit, such as uint8(300), is a compile error.

i := 42
f := float64(i) / 5
u := uint8(i)
back := int(f)
fmt.Println(f, u, back)
big := 300
fmt.Println(uint8(big), int8(big))
neg, pos := -3.9, 3.9
fmt.Println(int(neg), int(pos))// Output:
// 8.4 42 8
// 44 44
// -3 3

Strings and numbers with strconv

Atoi and Itoa are the int shortcuts; ParseInt takes a base and a bit size and reports range errors. string(65) is not "65": it is "A", the character with that code point.

n, err := strconv.Atoi("123")
fmt.Println(n, err)
_, err = strconv.Atoi("12a")
fmt.Println(err)
x, _ := strconv.ParseInt("ff", 16, 64)
fl, _ := strconv.ParseFloat("3.25", 64)
b, _ := strconv.ParseBool("true")
fmt.Println(x, fl, b)
fmt.Println(strconv.Itoa(99), strconv.FormatInt(255, 2), strconv.Quote("tab\there"))// Output:
// 123 <nil>
// strconv.Atoi: parsing "12a": invalid syntax
// 255 3.25 true
// 99 11111111 "tab\there"

Integer overflow wraps, division truncates

Integer arithmetic wraps around silently at run time. / on integers truncates toward zero and % keeps the sign of the left operand. For checked math, compare against math.MaxInt64 first or use math/big.

var b uint8 = 255
b++
var i int8 = 127
i++
fmt.Println(b, i)
fmt.Println(7/2, -7/2, 7%3, -7%3)
fmt.Println(7.0/2, math.Floor(-3.5), math.Round(2.5))// Output:
// 0 -128
// 3 -3 1 -1
// 3.5 -4 3

Integer division by zero panics

A constant divisor of 0 is a compile error; a variable one panics at run time. Floating point division by zero gives +Inf or NaN instead.

zero := 0
fmt.Println(10 / zero)// Output:
// panic: runtime error: integer divide by zero
//
// goroutine 1 [running]:

Defined Types and Aliases

A new type, or another name for one

type Celsius float64 creates a distinct type with its own methods, and mixing it with Fahrenheit needs a conversion. type Temp = Celsius is an alias: the same type under a second name, used mostly for gradual refactoring.

package main

import "fmt"

type Celsius float64
type Fahrenheit float64

func (c Celsius) ToF() Fahrenheit { return Fahrenheit(c*9/5 + 32) }

type Temp = Celsius

func main() {
    var t Temp = 21.5
    fmt.Println(t.ToF())
    fmt.Printf("%T\n", t)
}// Output:
// 70.7
// main.Celsius

Generic type aliases

Go 1.24+

Aliases can take type parameters since Go 1.24, which lets a package re-export a generic type from another package without wrapping it.

type Set[T comparable] = map[T]struct{}
type List[T any] = []T

Control Flow

if and switch

if with a short statement

Variables declared in the if statement live only in the if and its else branches. Parentheses around the condition are not allowed, and braces are always required.

if n, err := strconv.Atoi("42"); err != nil {
    fmt.Println("bad number:", err)
} else if n > 40 {
    fmt.Println("big", n)
} else {
    fmt.Println("small", n)
}// Output:
// big 42

switch: no fallthrough by default

Each case breaks automatically; fallthrough continues into the next case body without checking it. A switch with no value is a cleaner if-else chain.

day := "sat"
switch day {
case "sat", "sun":
    fmt.Println("weekend")
case "fri":
    fmt.Println("almost")
    fallthrough
default:
    fmt.Println("weekday")
}
x := 7
switch {
case x > 5:
    fmt.Println("more than 5")
case x > 0:
    fmt.Println("positive")
}// Output:
// weekend
// more than 5

for Loops

The only loop keyword

for with three parts is the C loop, with one condition it is a while loop, and with nothing it loops forever until break or return.

for i := 0; i < 3; i++ {
    fmt.Print(i, " ")
}
n := 1
for n < 100 {
    n *= 3
}
fmt.Println(n)
for {
    n--
    if n%10 == 0 {
        break
    }
}
fmt.Println(n)// Output:
// 0 1 2 243
// 240

range over ints, slices, maps and strings

Go 1.22+

range over an integer counts from 0 to n-1 (Go 1.22). Over a string, range yields byte offsets and runes, so the index jumps by 2 after the two-byte é. Map order is random on purpose.

for i := range 3 {
    fmt.Print(i, " ")
}
fmt.Println()
for i, v := range []string{"a", "b"} {
    fmt.Print(i, "=", v, " ")
}
fmt.Println()
for i, r := range "héllo" {
    fmt.Print(i, ":", string(r), " ")
}
fmt.Println()// Output:
// 0 1 2 
// 0=a 1=b 
// 0:h 1:é 3:l 4:l 5:o 

Each iteration has its own variable

Go 1.22+

Since Go 1.22 the loop variable is new in every iteration, so closures and goroutines see the value of their own iteration. Before, all three would print 3. The go line in go.mod decides which rule applies.

var prints []func()
for i := range 3 {
    prints = append(prints, func() { fmt.Print(i, " ") })
}
for _, p := range prints {
    p()
}
fmt.Println()// Output:
// 0 1 2 

Labels, break and continue

Break out of an outer loop

A label names a for, switch or select, and break or continue with the label acts on it. Plain break inside a select or switch only leaves that statement, a common surprise inside for-select loops.

grid := [][]int{{1, 2}, {3, -1}, {5, 6}}
outer:
for r, row := range grid {
    for c, v := range row {
        if v < 0 {
            fmt.Println("negative at", r, c)
            break outer
        }
    }
}
for i := range 5 {
    if i%2 == 0 {
        continue
    }
    fmt.Print(i, " ")
}
fmt.Println()// Output:
// negative at 1 1
// 1 3 

Strings, Runes & Bytes

String Basics

Strings are read-only bytes, usually UTF-8

len counts bytes, not characters: é takes 2 bytes and each Chinese character 3. Indexing gives a byte. Raw strings in backticks keep backslashes and newlines as they are, which suits regular expressions and paths.

s := "héllo, 世界"
fmt.Println(len(s), utf8.RuneCountInString(s))
fmt.Println(s[0], string(s[0]), s[1:3])
raw := `C:\path\no\escapes
two lines`
fmt.Println(raw)// Output:
// 14 9
// 104 h é
// C:\path\no\escapes
// two lines

Runes and bytes

[]rune(s) decodes to code points, []byte(s) copies the raw bytes; both allocate. A rune is an int32, so fmt prints a number unless you use %c or string(r).

s := "Go语言"
for i, r := range s {
    fmt.Printf("%d:%c(%U) ", i, r, r)
}
fmt.Println()
rs := []rune(s)
bs := []byte(s)
fmt.Println(len(rs), len(bs), string(rs[2:]))// Output:
// 0:G(U+0047) 1:o(U+006F) 2:语(U+8BED) 5:言(U+8A00) 
// 4 8 语言

Reverse a string by runes

Reversing bytes would break multi-byte characters. Combining marks such as an accent written as a separate code point still end up on the wrong letter; golang.org/x/text handles those grapheme clusters.

func reverse(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
}

func main() {
    fmt.Println(reverse("Hello, 世界"))
}// Output:
// 界世 ,olleH

The strings Package

Search and test

s := "Go is expressive, concise, clean"
fmt.Println(strings.Contains(s, "concise"), strings.HasPrefix(s, "Go"), strings.HasSuffix(s, "!"))
fmt.Println(strings.Index(s, "is"), strings.LastIndex(s, "c"), strings.Count(s, "c"))
fmt.Println(strings.EqualFold("Gopher", "GOPHER"), strings.ContainsAny(s, "xyz"))// Output:
// true true false
// 3 27 3
// true true

Split, join, trim and replace

Split keeps empty fields; Fields splits on any run of white space and drops empties. Trim removes a set of characters from both ends, TrimPrefix removes one exact prefix. strings.Title is deprecated: use golang.org/x/text/cases.

fmt.Printf("%q\n", strings.Split("a,b,,c", ","))
fmt.Printf("%q\n", strings.Fields("  a  b \t c\n"))
fmt.Println(strings.Join([]string{"x", "y", "z"}, "-"))
fmt.Printf("%q\n", strings.TrimSpace("  padded \n"))
fmt.Println(strings.Trim("xxhixx", "x"), strings.TrimPrefix("v1.2", "v"), strings.TrimSuffix("a.go", ".go"))
fmt.Println(strings.ReplaceAll("a-b-c", "-", "+"), strings.Replace("a-b-c", "-", "+", 1))
fmt.Println(strings.ToUpper("go"), strings.Repeat("ab", 3), strings.ToLower("MiXeD"))// Output:
// ["a" "b" "" "c"]
// ["a" "b" "c"]
// x-y-z
// "padded"
// hi 1.2 a
// a+b+c a+b-c
// GO ababab mixed

Cut, CutPrefix and CutLast

Go 1.27+

Cut (Go 1.18) replaces most Index plus slicing code. CutPrefix and CutSuffix arrived in Go 1.20, and CutLast, which splits around the last separator, in Go 1.27.

key, val, ok := strings.Cut("name=gopher=blue", "=")
fmt.Println(key, val, ok)
rest, found := strings.CutPrefix("Bearer abc123", "Bearer ")
fmt.Println(rest, found)
dir, file, _ := strings.CutLast("src/app/main.go", "/")
fmt.Println(dir, file)// Output:
// name gopher=blue true
// abc123 true
// src/app main.go

Iterate lines and fields without building a slice

Go 1.24+

Lines keeps the trailing newline of each line. SplitSeq, FieldsSeq and Lines return iterators, so a loop over a large string does not allocate a slice first.

text := "alpha\nbeta\ngamma"
for line := range strings.Lines(text) {
    fmt.Printf("%q ", line)
}
fmt.Println()
for part := range strings.SplitSeq("a,b,c", ",") {
    fmt.Print(part, " ")
}
fmt.Println()// Output:
// "alpha\n" "beta\n" "gamma" 
// a b c 

Building Strings

strings.Builder instead of += in a loop

s += x in a loop copies the whole string each time, which is quadratic. Builder grows one buffer; call b.Grow(n) first if you know the size. For a handful of pieces, + or fmt.Sprintf is fine.

var b strings.Builder
for i := range 3 {
    fmt.Fprintf(&b, "item%d;", i)
}
b.WriteString("done")
fmt.Println(b.String(), b.Len())// Output:
// item0;item1;item2;done 22

bytes: the same API for []byte

Package bytes mirrors strings for byte slices, which avoids converting back and forth when data comes from files or the network. bytes.Buffer is a growable buffer that implements io.Reader and io.Writer.

data := []byte("  Hello, Bytes  ")
data = bytes.TrimSpace(data)
fmt.Println(string(bytes.ToUpper(data)), bytes.Contains(data, []byte("Byte")))
var buf bytes.Buffer
buf.WriteString("line 1\n")
buf.WriteByte('x')
fmt.Printf("%q\n", buf.String())// Output:
// HELLO, BYTES true
// "line 1\nx"

Characters with unicode

Go 1.27 upgraded package unicode to Unicode 17, so newly added letters and emoji are classified correctly.

for _, r := range "Go 1.27!" {
    switch {
    case unicode.IsUpper(r):
        fmt.Print("U")
    case unicode.IsLetter(r):
        fmt.Print("l")
    case unicode.IsDigit(r):
        fmt.Print("d")
    case unicode.IsSpace(r):
        fmt.Print("_")
    default:
        fmt.Print(".")
    }
}
fmt.Println()// Output:
// Ul_d.dd.

Arrays & Slices

Arrays and Slices

Arrays are values, slices are views

An array's length is part of its type and assigning copies every element. A slice is a small header (pointer, length, capacity) over an array, so copies share the same elements. Almost all Go code uses slices.

a := [3]int{1, 2, 3}
b := a
b[0] = 99
fmt.Println(a, b, len(a))
s := []int{1, 2, 3}
t := s
t[0] = 99
fmt.Println(s, t)
auto := [...]string{"x", "y"}
fmt.Println(len(auto))// Output:
// [1 2 3] [99 2 3] 3
// [99 2 3] [99 2 3]
// 2

make, append, len and cap

append returns the slice, which may point to a new, larger array once capacity runs out, so always assign the result back. make([]T, 0, n) preallocates when you know the final size.

s := make([]int, 0, 2)
for i := range 5 {
    s = append(s, i)
    fmt.Println(len(s), cap(s), s)
}
s = append(s, []int{7, 8}...)
fmt.Println(s)// Output:
// 1 2 [0]
// 2 2 [0 1]
// 3 4 [0 1 2]
// 4 4 [0 1 2 3]
// 5 8 [0 1 2 3 4]
// [0 1 2 3 4 7 8]

Slicing shares the backing array

s[a:b] shares memory and its capacity reaches to the end of the original array, so append can overwrite elements the caller still uses. The full slice expression s[a:b:c] caps the capacity, forcing append to copy.

nums := []int{0, 1, 2, 3, 4, 5}
mid := nums[2:4]
mid[0] = 20
fmt.Println(nums, mid, len(mid), cap(mid))
mid = append(mid, 30)
fmt.Println(nums)
safe := nums[2:4:4]
safe = append(safe, 40)
fmt.Println(nums, safe)// Output:
// [0 1 20 3 4 5] [20 3] 2 4
// [0 1 20 3 30 5]
// [0 1 20 3 30 5] [20 3 40]

copy, clone, and 2D slices

copy copies min(len(dst), len(src)) elements and returns how many. There is no built-in 2D slice: make the outer slice, then each row.

src := []int{1, 2, 3}
dst := make([]int, 2)
n := copy(dst, src)
fmt.Println(n, dst)
c := slices.Clone(src)
c[0] = 100
fmt.Println(src, c)
grid := make([][]rune, 2)
for i := range grid {
    grid[i] = []rune("..")
}
grid[1][0] = '#'
for _, row := range grid {
    fmt.Println(string(row))
}// Output:
// 2 [1 2]
// [1 2 3] [100 2 3]
// ..
// #.

The slices Package

Go 1.21+

Sort, search and compare

Go 1.21+

The generic slices package replaced most uses of sort and hand-written loops in Go 1.21. Compact removes consecutive duplicates, so sort first to remove them all.

s := []int{5, 2, 8, 2, 9}
slices.Sort(s)
fmt.Println(s, slices.Contains(s, 8), slices.Index(s, 8))
i, found := slices.BinarySearch(s, 5)
fmt.Println(i, found, slices.Max(s), slices.Min(s))
fmt.Println(slices.Compact(s), slices.Equal([]int{1}, []int{1}))// Output:
// [2 2 5 8 9] true 3
// 2 true 9 2
// [2 5 8 9] true

Sort structs by a field

Go 1.22+

The compare function returns negative, zero or positive. cmp.Or (Go 1.22) returns its first non-zero argument, which chains sort keys: age descending, then name.

package main

import (
    "cmp"
    "fmt"
    "slices"
)

type User struct {
    Name string
    Age  int
}

func main() {
    users := []User{{"ann", 31}, {"bob", 25}, {"cid", 31}}
    slices.SortStableFunc(users, func(a, b User) int {
        return cmp.Or(cmp.Compare(b.Age, a.Age), cmp.Compare(a.Name, b.Name))
    })
    fmt.Println(users)
    idx := slices.IndexFunc(users, func(u User) bool { return u.Name == "bob" })
    fmt.Println(idx)
}// Output:
// [{ann 31} {cid 31} {bob 25}]
// 2

Insert, delete and filter in place

Delete and DeleteFunc zero the elements past the new length since Go 1.22, so dropped pointers can be garbage collected.

s := []string{"a", "b", "c", "d"}
s = slices.Insert(s, 1, "x")
s = slices.Delete(s, 3, 4)
fmt.Println(s)
nums := []int{1, 2, 3, 4, 5, 6}
nums = slices.DeleteFunc(nums, func(n int) bool { return n%2 == 0 })
slices.Reverse(nums)
fmt.Println(nums, len(nums))// Output:
// [a x b d]
// [5 3 1] 3

Chunks and repeats

Go 1.23+

Chunk yields sub-slices that share the original array. Repeat allocates a new slice.

for c := range slices.Chunk([]int{1, 2, 3, 4, 5}, 2) {
    fmt.Print(c, " ")
}
fmt.Println(slices.Repeat([]string{"ab"}, 3))// Output:
// [1 2] [3 4] [5] [ab ab ab]

Maps

Map Basics

Create, read, write, delete

Reading a missing key gives the zero value, so use the comma ok form when 0 is a valid value. delete on a missing key does nothing. fmt prints maps with sorted keys, but range order is random.

ages := map[string]int{"ann": 31, "bob": 25}
ages["cid"] = 40
fmt.Println(ages["ann"], ages["zoe"], len(ages))
age, ok := ages["zoe"]
fmt.Println(age, ok)
delete(ages, "bob")
if v, ok := ages["cid"]; ok {
    fmt.Println("cid is", v)
}
fmt.Println(ages)// Output:
// 31 0 3
// 0 false
// cid is 40
// map[ann:31 cid:40]

Writing to a nil map panics

A declared but unmade map is nil: reading works, writing panics. Create it with make(map[K]V) or a literal, and in structs, in a constructor.

var m map[string]int
fmt.Println(m["x"], len(m))
m["x"] = 1// Output:
// 0 0
// panic: assignment to entry in nil map
//
// goroutine 1 [running]:

Iterate in a stable order

Go 1.23+

Map iteration order is deliberately randomized. maps.Keys returns an iterator and slices.Sorted collects and sorts it, both since Go 1.23.

stock := map[string]int{"pear": 3, "apple": 5, "fig": 1}
for _, k := range slices.Sorted(maps.Keys(stock)) {
    fmt.Println(k, stock[k])
}// Output:
// apple 5
// fig 1
// pear 3

Common Map Patterns

Counting, grouping and sets

count[w]++ works on a missing key because it starts at zero, and append works on a nil slice. map[K]struct{} is a set whose values take no memory.

words := strings.Fields("the cat and the hat and the bat")
count := map[string]int{}
for _, w := range words {
    count[w]++
}
byLen := map[int][]string{}
for w := range count {
    byLen[len(w)] = append(byLen[len(w)], w)
}
seen := map[string]struct{}{}
seen["the"] = struct{}{}
_, dup := seen["the"]
fmt.Println(count["the"], len(byLen[3]), dup)// Output:
// 3 5 true

Map values are not addressable

A map element may move when the map grows, so you cannot take its address or assign to a field of it. Read, change and write back the whole value, or store pointers: map[string]*Point.

package main

type Point struct{ X, Y int }

func main() {
    m := map[string]Point{"a": {1, 2}}
    m["a"].X = 10
}// Output:
// # command-line-arguments
// ./main.go:7:5: cannot assign to struct field m["a"].X in map

The maps package and clear

Go 1.21+

clear (Go 1.21) deletes every entry but keeps the allocated space for reuse. maps.Clone is a shallow copy: slices or pointers inside are still shared.

a := map[string]int{"x": 1, "y": 2}
b := maps.Clone(a)
maps.Copy(b, map[string]int{"z": 3})
maps.DeleteFunc(b, func(k string, v int) bool { return v == 1 })
fmt.Println(a, b, maps.Equal(a, b))
clear(a)
fmt.Println(a, len(a))// Output:
// map[x:1 y:2] map[y:2 z:3] false
// map[] 0

Maps are not safe for concurrent writes

The runtime detects concurrent map writes on a best effort basis and stops the whole program; it cannot be recovered. Guard the map with a sync.Mutex, or use sync.Map for keys that are written once and read many times.

m := map[int]int{}
var wg sync.WaitGroup
for i := range 100 {
    wg.Go(func() { m[i] = i })
}
wg.Wait()// Output:
// fatal error: concurrent map writes

Structs & Embedding

Structs

Define, create and use

Name the fields in literals: positional literals break when a field is added. p.Admin works through a pointer without (*p).Admin. Structs compare with == when all their fields are comparable.

package main

import "fmt"

type User struct {
    ID     int
    Name   string
    Emails []string
    Admin  bool
}

func main() {
    u := User{ID: 1, Name: "ann"}
    u.Emails = append(u.Emails, "ann@example.com")
    p := &u
    p.Admin = true
    fmt.Printf("%v\n%+v\n", u, u)
    point := struct{ X, Y int }{3, 4}
    fmt.Println(point.X, point == struct{ X, Y int }{3, 4})
}// Output:
// {1 ann [ann@example.com] true}
// {ID:1 Name:ann Emails:[ann@example.com] Admin:true}
// 3 true

Constructors and functional options

Go has no constructors; a NewT function sets defaults and invariants. Functional options keep the signature stable as settings are added, which suits library APIs; a Config struct is simpler for applications.

package main

import (
    "fmt"
    "time"
)

type Server struct {
    addr    string
    timeout time.Duration
}

type Option func(*Server)

func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }

func NewServer(addr string, opts ...Option) *Server {
    s := &Server{addr: addr, timeout: 30 * time.Second}
    for _, o := range opts {
        o(s)
    }
    return s
}

func main() {
    s := NewServer(":8080", WithTimeout(5*time.Second))
    fmt.Println(s.addr, s.timeout)
}// Output:
// :8080 5s

Embedding

Composition with promoted fields and methods

An embedded type's fields and methods are promoted to the outer struct, and the outer type satisfies the same interfaces. It is composition, not inheritance: Hello still receives a Person.

package main

import "fmt"

type Person struct{ Name string }

func (p Person) Hello() string { return "hi, I am " + p.Name }

type Employee struct {
    Person
    Company string
}

func main() {
    e := Employee{Person: Person{Name: "ann"}, Company: "acme"}
    fmt.Println(e.Name, e.Hello(), e.Person.Name)
}// Output:
// ann hi, I am ann ann

Promoted field names in struct literals

Go 1.27+

Before Go 1.27 this was unknown field X; the literal had to spell Pin{Point: Point{X: 1, Y: 2}, Label: "home"}.

package main

import "fmt"

type Point struct{ X, Y int }

type Pin struct {
    Point
    Label string
}

func main() {
    p := Pin{X: 1, Y: 2, Label: "home"}
    fmt.Printf("%+v\n", p)
}// Output:
// {Point:{X:1 Y:2} Label:home}

Tags and Layout

Read struct tags with reflect

Go 1.26+

Tags are key:"value" pairs separated by spaces; a space after the colon silently breaks them, which go vet reports. reflect.TypeFor arrived in Go 1.22 and the Type.Fields iterator in Go 1.26.

package main

import (
    "fmt"
    "reflect"
)

type Item struct {
    SKU   string  `json:"sku" db:"sku_code"`
    Price float64 `json:"price,omitzero"`
}

func main() {
    t := reflect.TypeFor[Item]()
    for f := range t.Fields() {
        fmt.Println(f.Name, f.Tag.Get("json"), f.Tag.Get("db"))
    }
}// Output:
// SKU sku sku_code
// Price price,omitzero 

Field order changes the size

Fields are aligned to their size, so padding fills the gaps. Ordering from largest to smallest alignment saves memory in large slices; the struct layout tool above does the arithmetic. struct{} takes no space at all.

package main

import (
    "fmt"
    "unsafe"
)

type Loose struct {
    a bool
    b int64
    c bool
}

type Tight struct {
    b int64
    a bool
    c bool
}

func main() {
    fmt.Println(unsafe.Sizeof(Loose{}), unsafe.Sizeof(Tight{}), unsafe.Sizeof(struct{}{}))
}// Output:
// 24 16 0

Pointers & Memory

Pointers

& takes an address, * follows it

There is no pointer arithmetic in Go outside package unsafe, and returning a pointer to a local variable is safe: the compiler moves it to the heap when it outlives the function.

x := 10
p := &x
*p = 20
fmt.Println(x, *p, p != nil)
var q *int
fmt.Println(q == nil)// Output:
// 20 20 true
// true

Everything is passed by value

Arguments are copies. A struct copy does not change the caller's struct; a pointer copy points at the same one. Slices, maps and channels contain pointers, so a function can change their elements, but append to a slice parameter is not seen by the caller.

package main

import "fmt"

type Counter struct{ N int }

func incValue(c Counter)    { c.N++ }
func incPointer(c *Counter) { c.N++ }
func addItem(s []int)       { s[0] = 99 }

func main() {
    c := Counter{}
    incValue(c)
    incPointer(&c)
    s := []int{1, 2}
    addItem(s)
    fmt.Println(c.N, s)
}// Output:
// 1 [99 2]

nil pointer dereference

Check for nil before following pointers that may be unset, such as optional struct fields and map values of pointer type. The panic message and the line in the trace point to the exact access.

package main

import "fmt"

type Node struct{ Val int }

func main() {
    var n *Node
    fmt.Println(n == nil)
    fmt.Println(n.Val)
}// Output:
// true
// panic: runtime error: invalid memory address or nil pointer dereference
// [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x491df1]
//
// goroutine 1 [running]:

Memory and the Garbage Collector

See what escapes to the heap

Values that outlive their function, or are too large or dynamically sized, go on the heap and cost garbage collection. Returning values instead of pointers, and preallocating slices, keeps hot paths on the stack.

go build -gcflags=-m ./... 2>&1 | grep escape// Output:
// ./main.go:14:9: &User{...} escapes to heap
// ./main.go:21:13: ... argument does not escape

Tune the collector

Go 1.26 made the Green Tea collector the default, cutting GC overhead by 10 to 40 percent on typical programs. GOMEMLIMIT (Go 1.19) makes the collector work harder as the process nears the limit instead of running out of memory.

GOGC=200 ./app              # collect less often, use more memory

GOMEMLIMIT=1GiB ./app       # soft memory limit, useful in containers

GODEBUG=gctrace=1 ./app     # one line per collection

debug.SetMemoryLimit(1 << 30)

Weak pointers and cleanups

Go 1.24+

A weak pointer does not keep its object alive, which suits caches. runtime.AddCleanup replaces SetFinalizer: the cleanup gets a separate argument and must not refer to the object, and it runs on a background goroutine after a collection.

package main

import (
    "fmt"
    "runtime"
    "time"
    "weak"
)

type Blob struct{ data []byte }

func main() {
    done := make(chan int, 1)
    b := &Blob{data: make([]byte, 1<<20)}
    w := weak.Make(b)
    runtime.AddCleanup(b, func(n int) { done <- n }, len(b.data))
    fmt.Println("alive:", w.Value() != nil)
    b = nil
    runtime.GC()
    select {
    case n := <-done:
        fmt.Println("cleaned up", n, "bytes, weak pointer nil:", w.Value() == nil)
    case <-time.After(time.Second):
        fmt.Println("no cleanup yet")
    }
}// Output:
// alive: true
// cleaned up 1048576 bytes, weak pointer nil: true

Functions & Closures

Functions

Multiple results and named results

Returning (value, error) is the Go convention for anything that can fail. Named results document what comes back and allow a bare return, which is best kept to short functions.

package main

import (
    "errors"
    "fmt"
)

func divmod(a, b int) (q, r int, err error) {
    if b == 0 {
        return 0, 0, errors.New("division by zero")
    }
    q, r = a/b, a%b
    return
}

func main() {
    q, r, err := divmod(17, 5)
    fmt.Println(q, r, err)
    _, _, err = divmod(1, 0)
    fmt.Println(err)
}// Output:
// 3 2 <nil>
// division by zero

Variadic parameters

Inside the function nums is a []int. Passing xs... hands over the slice itself, without a copy, so the function can modify the caller's elements.

func sum(label string, nums ...int) string {
    total := 0
    for _, n := range nums {
        total += n
    }
    return fmt.Sprintf("%s=%d (%d args)", label, total, len(nums))
}

func main() {
    fmt.Println(sum("none"))
    fmt.Println(sum("three", 1, 2, 3))
    xs := []int{4, 5}
    fmt.Println(sum("slice", xs...))
}// Output:
// none=0 (0 args)
// three=6 (3 args)
// slice=9 (2 args)

Closures

A function that remembers its variables

The closure captures the variable n itself, not a copy, and keeps it alive after counter returns. Each call to counter makes a new n.

func counter() func() int {
    n := 0
    return func() int {
        n++
        return n
    }
}

func main() {
    next := counter()
    fmt.Println(next(), next(), next())
    other := counter()
    fmt.Println(other())
}// Output:
// 1 2 3
// 1

Function types and method values

Functions are values with a type, and r.Replace is a method value: a function bound to its receiver. Function values can only be compared with nil.

package main

import (
    "fmt"
    "strings"
)

type Transform func(string) string

func apply(s string, fs ...Transform) string {
    for _, f := range fs {
        s = f(s)
    }
    return s
}

func main() {
    r := strings.NewReplacer("a", "4", "e", "3")
    fmt.Println(apply("  leet speak ", strings.TrimSpace, strings.ToUpper))
    fmt.Println(apply("leet speak", r.Replace))
}// Output:
// LEET SPEAK
// l33t sp34k

defer

Runs at return, last in first out

Deferred calls run when the function returns, in reverse order, even after a panic. Their arguments are evaluated when the defer statement runs, which is why x was 10.

func main() {
    for i := range 3 {
        defer fmt.Println("deferred", i)
    }
    x := 10
    defer fmt.Println("x was", x)
    x = 20
    fmt.Println("body done, x =", x)
}// Output:
// body done, x = 20
// x was 10
// deferred 2
// deferred 1
// deferred 0

Clean up right after acquiring

Put the defer right after the successful acquire so every return path releases the resource. For files you write, check the error of Close too: a failed Close can mean lost data.

f, err := os.Open(path)
if err != nil {
    return err
}
defer f.Close()

mu.Lock()
defer mu.Unlock()

defer can change named results

A deferred closure runs after the return value is set and can still change a named result. That is how close errors and recovered panics are reported to the caller.

package main

import (
    "errors"
    "fmt"
)

func closeFile() error { return errors.New("close failed: disk full") }

func save() (err error) {
    defer func() {
        if cerr := closeFile(); cerr != nil && err == nil {
            err = cerr
        }
    }()
    return nil
}

func main() {
    fmt.Println(save())
}// Output:
// close failed: disk full

Methods & Interfaces

Methods

Value and pointer receivers

A pointer receiver can modify the value and avoids copying large structs. r.Scale works on an addressable value because Go takes &r for you. Pick one kind per type: if any method needs a pointer, make them all pointer receivers.

package main

import "fmt"

type Rect struct{ W, H float64 }

func (r Rect) Area() float64 { return r.W * r.H }

func (r *Rect) Scale(f float64) {
    r.W *= f
    r.H *= f
}

func main() {
    r := Rect{2, 3}
    r.Scale(2)
    fmt.Println(r, r.Area())
}// Output:
// {4 6} 24

Methods on any defined type

Methods can be declared on any type defined in the same package: slices, maps, funcs, numbers. A String method makes fmt print the value your way.

package main

import (
    "fmt"
    "strings"
)

type Tags []string

func (t Tags) String() string { return "#" + strings.Join(t, " #") }

func (t Tags) Has(s string) bool {
    for _, x := range t {
        if x == s {
            return true
        }
    }
    return false
}

func main() {
    t := Tags{"go", "cli"}
    fmt.Println(t, t.Has("go"))
}// Output:
// #go #cli true

Interfaces

Implemented implicitly

There is no implements keyword: a type satisfies an interface by having its methods. Define small interfaces where they are used, not next to the types, and return concrete types from constructors.

package main

import (
    "fmt"
    "math"
)

type Shape interface {
    Area() float64
}

type Circle struct{ R float64 }
type Square struct{ S float64 }

func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (s Square) Area() float64 { return s.S * s.S }

func total(shapes ...Shape) (sum float64) {
    for _, s := range shapes {
        sum += s.Area()
    }
    return
}

func main() {
    fmt.Printf("%.2f\n", total(Circle{1}, Square{2}))
}// Output:
// 7.14

Type assertions and type switches

v.(T) without the comma ok form panics when v is not a T. In a type switch with several types in one case, x keeps the interface type.

func describe(v any) string {
    switch x := v.(type) {
    case nil:
        return "nil"
    case int, int64:
        return fmt.Sprintf("integer %v", x)
    case string:
        return "string of " + strconv.Itoa(len(x)) + " bytes"
    case fmt.Stringer:
        return "stringer " + x.String()
    default:
        return fmt.Sprintf("other %T", x)
    }
}

func main() {
    fmt.Println(describe(42), "|", describe("hi"), "|", describe(time.Second), "|", describe(2.5))
    var v any = "text"
    s, ok := v.(string)
    n, ok2 := v.(int)
    fmt.Println(s, ok, n, ok2)
}// Output:
// integer 42 | string of 2 bytes | stringer 1s | other float64
// text true 0 false

An interface holding a nil pointer is not nil

An interface is nil only when both its type and value are nil. Returning a nil *MyErr as error gives a non-nil interface, so err != nil is true. Return a literal nil on the success path.

package main

import "fmt"

type MyErr struct{}

func (*MyErr) Error() string { return "my error" }

func find(fail bool) error {
    var e *MyErr
    if fail {
        e = &MyErr{}
    }
    return e
}

func main() {
    err := find(false)
    fmt.Println(err == nil, err)
}// Output:
// false my error

Pointer methods and method sets

Only *Dog has the Speak method, so a Dog value does not satisfy Speaker. Use &Dog{}, or give the method a value receiver if it does not modify the dog.

package main

import "fmt"

type Speaker interface{ Speak() string }

type Dog struct{}

func (d *Dog) Speak() string { return "woof" }

func main() {
    var s Speaker = Dog{}
    fmt.Println(s.Speak())
}// Output:
// # command-line-arguments
// ./main.go:12:21: cannot use Dog{} (value of struct type Dog) as Speaker value in variable declaration: Dog does not implement Speaker (method Speak has pointer receiver)

Composing interfaces

io.Reader and io.Writer, one method each, are the most reused interfaces in Go: files, network connections, gzip streams, hashes and HTTP bodies all fit them, so one function can work with all of them.

type Reader interface{ Read(p []byte) (n int, err error) }
type Writer interface{ Write(p []byte) (n int, err error) }
type ReadWriter interface {
    Reader
    Writer
}

var _ io.ReadWriter = (*bytes.Buffer)(nil)

Generics

Generic Functions

Go 1.18+

Type parameters and constraints

Type arguments are usually inferred from the arguments. any accepts every type, comparable those usable with ==, and cmp.Ordered those usable with < and >. max and min became built-ins in Go 1.21.

package main

import (
    "cmp"
    "fmt"
)

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
}

func MaxOf[T cmp.Ordered](xs ...T) T {
    m := xs[0]
    for _, x := range xs[1:] {
        m = max(m, x)
    }
    return m
}

func main() {
    lens := Map([]string{"go", "rust", "c"}, func(s string) int { return len(s) })
    fmt.Println(lens, MaxOf(3, 9, 4), MaxOf("pear", "apple"))
}// Output:
// [2 4 1] 9 pear

Your own constraints with unions and ~

~int64 means any type whose underlying type is int64, so the defined type Cents qualifies. An interface with a type union can only be used as a constraint, not as a normal variable type.

package main

import "fmt"

type Number interface {
    ~int | ~int64 | ~float64
}

func Sum[T Number](xs []T) T {
    var total T
    for _, x := range xs {
        total += x
    }
    return total
}

type Cents int64

func main() {
    fmt.Println(Sum([]int{1, 2, 3}), Sum([]float64{0.5, 0.25}), Sum([]Cents{199, 1}))
}// Output:
// 6 0.75 200

Generic Types

A generic stack

var zero T is how you get the zero value of a type parameter. Methods of a generic type use the type's parameters, written Stack[T] in the receiver.

package main

import "fmt"

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
}

func main() {
    var s Stack[string]
    s.Push("a")
    s.Push("b")
    v, ok := s.Pop()
    fmt.Println(v, ok, len(s.items))
}// Output:
// b true 1

Generic methods

Go 1.27+

Since Go 1.27 a method can declare its own type parameters. Interfaces still cannot have generic methods, so a generic method never satisfies an interface method. math/rand/v2 uses this for Rand.N.

package main

import (
    "fmt"
    "strconv"
)

type List struct{ items []int }

func (l List) Map[U any](f func(int) U) []U {
    out := make([]U, len(l.items))
    for i, v := range l.items {
        out[i] = f(v)
    }
    return out
}

func main() {
    l := List{items: []int{1, 2, 3}}
    fmt.Printf("%q\n", l.Map(strconv.Itoa))
    fmt.Println(l.Map(func(v int) bool { return v%2 == 1 }))
}// Output:
// ["1" "2" "3"]
// [true false true]

Constraints that refer to themselves

Go 1.26+

Go 1.26 lets a generic type mention itself in its own type parameter list, the pattern other languages call F-bounded polymorphism.

package main

import "fmt"

type Adder[A Adder[A]] interface {
    Add(A) A
}

type Money int

func (m Money) Add(o Money) Money { return m + o }

func Total[A Adder[A]](xs ...A) A {
    var t A
    for _, x := range xs {
        t = t.Add(x)
    }
    return t
}

func main() {
    fmt.Println(Total(Money(5), Money(7)))
}// Output:
// 12

Inference when converting a generic function

Go 1.27+

Assigning a generic function to a typed variable already inferred T; Go 1.27 extends inference to conversions and every other place where the target function type is known.

package main

import "fmt"

func Double[T int | float64](x T) T { return x * 2 }

func main() {
    var f func(float64) float64 = Double
    g := (func(int) int)(Double)
    fmt.Println(f(1.5), g(21))
}// Output:
// 3 42

When to Use Generics

Rules of thumb

Use generics forPrefer instead
Containers: sets, stacks, caches, treesan interface, when behavior differs per type
Functions over slices, maps and channels of any elementa plain function, when there is only one type today
Removing copies of the same algorithm for int, float64, stringcode generation, rarely needed since Go 1.18
Type safe wrappers around any-based APIsreflection, when the type is only known at run time

Errors, panic & recover

Creating and Checking Errors

Wrap with %w, check with errors.Is

%w keeps the original error inside the new one, so errors.Is finds it however deep the wrapping goes, while == only matches the outermost value. Add context once per layer: what was being done, and with which input.

package main

import (
    "errors"
    "fmt"
    "io/fs"
    "os"
)

var ErrNotFound = errors.New("not found")

func loadUser(id int) error {
    return fmt.Errorf("load user %d: %w", id, ErrNotFound)
}

func main() {
    err := loadUser(7)
    fmt.Println(err)
    fmt.Println(errors.Is(err, ErrNotFound), err == ErrNotFound)
    _, err = os.ReadFile("/no/such/file")
    fmt.Println(errors.Is(err, fs.ErrNotExist))
}// Output:
// load user 7: not found
// true false
// true

Custom error types and errors.AsType

Go 1.26+

errors.AsType (Go 1.26) is the generic, type safe form of errors.As: no pointer variable to declare and no way to pass the wrong kind of target.

package main

import (
    "errors"
    "fmt"
)

type ValidationError struct {
    Field string
}

func (e *ValidationError) Error() string { return "invalid " + e.Field }

func save() error {
    return fmt.Errorf("save: %w", &ValidationError{Field: "email"})
}

func main() {
    err := save()
    if ve, ok := errors.AsType[*ValidationError](err); ok {
        fmt.Println("field:", ve.Field)
    }
    var ve *ValidationError
    fmt.Println(errors.As(err, &ve), ve.Field)
}// Output:
// field: email
// true email

Several errors at once

Go 1.20+

errors.Join drops nil errors and prints one per line. fmt.Errorf with several %w verbs wraps them all; errors.Is and errors.As search every branch.

err := errors.Join(errors.New("name is empty"), nil, errors.New("age is negative"))
fmt.Println(err)
multi := fmt.Errorf("validate: %w; also %w", io.EOF, os.ErrClosed)
fmt.Println(errors.Is(multi, io.EOF), errors.Is(multi, os.ErrClosed))// Output:
// name is empty
// age is negative
// true true

panic and recover

Turn a panic into an error

recover only works inside a deferred function, and only stops a panic in the same goroutine. Use panic for bugs and impossible states, not for expected failures such as bad input or a missing file.

package main

import "fmt"

func safeDiv(a, b int) (q int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered: %v", r)
        }
    }()
    return a / b, nil
}

func main() {
    fmt.Println(safeDiv(10, 2))
    fmt.Println(safeDiv(1, 0))
}// Output:
// 5 <nil>
// 0 recovered: runtime error: integer divide by zero

Must helpers for startup code

MustX panics on error, which is right for values fixed in the source code: a bad pattern is a bug that should stop the program at startup, not an error to handle.

var tmpl = template.Must(template.New("t").Parse("Hello, {{.}}\n"))
var re = regexp.MustCompile(`^\d{3}-\d{4}$`)

func main() {
    if err := tmpl.Execute(os.Stdout, "Gopher"); err != nil {
        log.Fatal(err)
    }
    fmt.Println(re.MatchString("555-0100"))
}// Output:
// Hello, Gopher
// true

An unrecovered panic in any goroutine kills the program

recover in main does not catch a panic in another goroutine. Long running goroutines, such as workers, should recover at their top level and report the error.

go func() {
    panic("worker failed")
}()
time.Sleep(time.Second)
fmt.Println("never printed")// Output:
// panic: worker failed
//
// goroutine 7 [running]:

Iterators

Range over Functions

Go 1.23+

An iter.Seq is a function that calls yield

Go 1.23+

The loop body becomes the yield function. When the loop breaks, yield returns false and the iterator must stop; calling yield again after that panics.

package main

import (
    "fmt"
    "iter"
)

func Countdown(from int) iter.Seq[int] {
    return func(yield func(int) bool) {
        for i := from; i > 0; i-- {
            if !yield(i) {
                return
            }
        }
    }
}

func main() {
    for n := range Countdown(5) {
        if n == 2 {
            break
        }
        fmt.Print(n, " ")
    }
    fmt.Println()
}// Output:
// 5 4 3 

Key and value pairs with iter.Seq2

Go 1.23+

package main

import (
    "fmt"
    "iter"
    "strings"
)

func Words(s string) iter.Seq2[int, string] {
    return func(yield func(int, string) bool) {
        for i, w := range strings.Fields(s) {
            if !yield(i, w) {
                return
            }
        }
    }
}

func main() {
    for i, w := range Words("iterators are just functions") {
        fmt.Println(i, w)
    }
}// Output:
// 0 iterators
// 1 are
// 2 just
// 3 functions

Iterator Helpers

Go 1.23+

slices and maps speak iterators

Go 1.23+

slices.All, Values and Backward produce iterators; Collect, Sorted and AppendSeq consume them. maps.Keys, Values and All do the same for maps, and maps.Collect builds a map from a Seq2.

names := []string{"cid", "ann", "bob"}
for i, v := range slices.Backward(names) {
    fmt.Print(i, ":", v, " ")
}
fmt.Println()
sorted := slices.Sorted(slices.Values(names))
upper := slices.Collect(func(yield func(string) bool) {
    for _, n := range sorted {
        if !yield(strings.ToUpper(n)) {
            return
        }
    }
})
fmt.Println(sorted, upper)
m := map[string]int{"a": 1, "b": 2}
fmt.Println(slices.Sorted(maps.Values(m)), len(maps.Collect(maps.All(m))))// Output:
// 2:bob 1:ann 0:cid 
// [ann bob cid] [ANN BOB CID]
// [1 2] 2

A generic Filter

Go 1.23+

Iterators compose lazily: nothing runs until a loop or a consumer such as slices.Collect pulls values, and a break stops the whole chain.

package main

import (
    "fmt"
    "iter"
    "slices"
)

func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
    return func(yield func(T) bool) {
        for v := range seq {
            if keep(v) && !yield(v) {
                return
            }
        }
    }
}

func main() {
    evens := Filter(slices.Values([]int{1, 2, 3, 4, 5, 6}), func(n int) bool { return n%2 == 0 })
    fmt.Println(slices.Collect(evens))
}// Output:
// [2 4 6]

Pull iterators

Go 1.23+

iter.Pull turns a push iterator into a next function, which is what you need to walk two sequences side by side. Always call stop, or the iterator's resources leak.

next, stop := iter.Pull(slices.Values([]string{"a", "b", "c"}))
defer stop()
for {
    v, ok := next()
    if !ok {
        break
    }
    fmt.Print(v, " ")
}
fmt.Println()// Output:
// a b c 

Goroutines & WaitGroup

Starting and Waiting

go starts a goroutine, WaitGroup waits

Go 1.25+

wg.Go (Go 1.25) calls Add, starts the goroutine and calls Done when it returns. Each goroutine writes its own slice element, so no lock is needed; the order of execution is not defined, only the result is.

results := make([]string, 3)
var wg sync.WaitGroup
for i, name := range []string{"ann", "bob", "cid"} {
    wg.Go(func() {
        results[i] = strings.ToUpper(name)
    })
}
wg.Wait()
fmt.Println(results)// Output:
// [ANN BOB CID]

The classic Add and Done form

Call Add before the go statement, never inside the goroutine, or Wait may return first. main returning ends the program without waiting for any goroutine.

var wg sync.WaitGroup
var mu sync.Mutex
total := 0
for i := 1; i <= 100; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        total += i
        mu.Unlock()
    }()
}
wg.Wait()
fmt.Println(total)// Output:
// 5050

How many threads and goroutines

GOMAXPROCS is how many threads run Go code at once. Since Go 1.25 its default respects the container's CPU limit on Linux and follows changes to it, so a pod limited to 2 CPUs no longer starts 64 threads.

fmt.Println(runtime.NumCPU() > 0, runtime.GOMAXPROCS(0) > 0, runtime.NumGoroutine())// Output:
// true true 1

Goroutines Are Cheap

A hundred thousand goroutines

A goroutine starts with a 2 KB stack that grows on demand, so hundreds of thousands fit in memory where the same number of OS threads would not. Cheap does not mean free: unbounded fan-out still needs a limit, shown in the patterns section.

var wg sync.WaitGroup
var done atomic.Int64
for range 100_000 {
    wg.Go(func() {
        done.Add(1)
    })
}
wg.Wait()
fmt.Println(done.Load(), "goroutines finished")// Output:
// 100000 goroutines finished

Leaks and Errors

A goroutine blocked forever is a leak

Only one goroutine is received from; the others block on ch forever and keep their memory. Make the channel buffered with len(urls), or cancel the rest with a context. The goroutineleak profile in Go 1.27 finds goroutines stuck like this.

func first(urls []string) string {
    ch := make(chan string)
    for _, u := range urls {
        go func() { ch <- fetch(u) }()
    }
    return <-ch
}

errgroup: wait and return the first error

golang.org/x module

golang.org/x/sync/errgroup cancels the context when one goroutine fails, returns that first error from Wait, and SetLimit caps how many run at once.

g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
for _, url := range urls {
    g.Go(func() error {
        return fetch(ctx, url)
    })
}
if err := g.Wait(); err != nil {
    return err
}

Channels & select

Channel Basics

Unbuffered channels synchronize

A send on an unbuffered channel waits until another goroutine receives, so the two meet at that point. That handoff is also a memory synchronization point.

ch := make(chan string)
go func() {
    ch <- "ping"
}()
msg := <-ch
fmt.Println(msg)// Output:
// ping

Buffered channels, close and range

A buffered send only waits when the buffer is full. After close, receivers drain what is left, then get the zero value and ok == false, and range ends. Only the sender should close, and sending on a closed channel panics.

jobs := make(chan int, 3)
jobs <- 1
jobs <- 2
fmt.Println(len(jobs), cap(jobs))
close(jobs)
for j := range jobs {
    fmt.Print(j, " ")
}
v, ok := <-jobs
fmt.Println(v, ok)// Output:
// 2 3
// 1 2 0 false

Deadlock

The send waits for a receiver that can never arrive because the same goroutine would have to run it. When every goroutine is blocked, the runtime stops the program with this message.

ch := make(chan int)
ch <- 1
fmt.Println(<-ch)// Output:
// fatal error: all goroutines are asleep - deadlock!
//
// goroutine 1 [chan send]:

select

Wait on several channels, with a timeout

select blocks until one case can proceed and picks randomly when several can. time.After returns a channel that receives after the duration; since Go 1.23 unreferenced timers are collected even if never fired.

fast := make(chan string, 1)
slow := make(chan string, 1)
go func() { time.Sleep(10 * time.Millisecond); fast <- "fast" }()
go func() { time.Sleep(2 * time.Second); slow <- "slow" }()
for range 2 {
    select {
    case m := <-fast:
        fmt.Println(m)
    case m := <-slow:
        fmt.Println(m)
    case <-time.After(200 * time.Millisecond):
        fmt.Println("timeout")
    }
}// Output:
// fast
// timeout

Non-blocking send and receive

A default case runs when no other case is ready, which turns select into a try-send or try-receive. Useful for dropping metrics under load instead of blocking.

ch := make(chan int, 1)
for i := range 3 {
    select {
    case ch <- i:
        fmt.Println("sent", i)
    default:
        fmt.Println("full, dropped", i)
    }
}
select {
case v := <-ch:
    fmt.Println("got", v)
default:
    fmt.Println("empty")
}// Output:
// sent 0
// full, dropped 1
// full, dropped 2
// got 0

Direction in types, nil to disable a case

chan<- int can only send and <-chan int can only receive, which the compiler enforces. Setting a channel variable to nil inside a select loop turns that case off, for example after its channel is closed.

func producer(out chan<- int) {
    for i := range 3 {
        out <- i
    }
    close(out)
}

func consumer(in <-chan int) (sum int) {
    for v := range in {
        sum += v
    }
    return
}

func main() {
    ch := make(chan int)
    go producer(ch)
    fmt.Println(consumer(ch))
    var off chan int
    select {
    case <-off:
        fmt.Println("never")
    default:
        fmt.Println("a nil channel is never ready")
    }
}// Output:
// 3
// a nil channel is never ready

Channel Rules

What each operation does

Operationnil channelopen channelclosed channel
Send ch <- vblocks foreverwaits for room or a receiverpanics
Receive <-chblocks foreverwaits for a valuezero value, ok is false
close(ch)panicsclosespanics
len(ch), cap(ch)0items in buffer, buffer sizeitems left, buffer size

Mutexes & Atomics

Mutexes

Guard shared state with a Mutex

The zero Mutex is unlocked and ready. Put it next to the fields it guards, use pointer receivers, and never copy a struct that contains one: go vet's copylocks check catches copies.

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    mu sync.Mutex
    m  map[string]int
}

func (c *Counter) Inc(key string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.m[key]++
}

func main() {
    c := Counter{m: map[string]int{}}
    var wg sync.WaitGroup
    for range 1000 {
        wg.Go(func() { c.Inc("hits") })
    }
    wg.Wait()
    fmt.Println(c.m["hits"])
}// Output:
// 1000

RWMutex for read-heavy data

Many readers can hold RLock together; Lock waits for all of them. It only pays off when reads greatly outnumber writes and the critical section is not tiny; otherwise a plain Mutex is faster.

type Cache struct {
    mu   sync.RWMutex
    data map[string]string
}

func (c *Cache) Get(k string) (string, bool) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    v, ok := c.data[k]
    return v, ok
}

func (c *Cache) Set(k, v string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.data[k] = v
}

Once, Atomics, Map and Pool

Run once, lazily

Go 1.21+

sync.OnceValue and OnceFunc (Go 1.21) wrap sync.Once around a function: the first call runs it, every later call returns the same result, safely from any goroutine.

var config = sync.OnceValue(func() map[string]string {
    fmt.Println("loading config")
    return map[string]string{"env": "prod"}
})

func main() {
    fmt.Println(config()["env"])
    fmt.Println(config()["env"])
}// Output:
// loading config
// prod
// prod

Typed atomics

Go 1.19+

atomic.Int64, Bool and Pointer[T] cannot be accessed non-atomically by mistake and are always 64-bit aligned, even on 32-bit targets. go fix in Go 1.27 rewrites the old atomic.AddInt64 style calls.

var hits atomic.Int64
var ready atomic.Bool
var wg sync.WaitGroup
for range 500 {
    wg.Go(func() { hits.Add(1) })
}
wg.Wait()
ready.Store(true)
fmt.Println(hits.Load(), ready.Load(), hits.CompareAndSwap(500, 0), hits.Load())// Output:
// 500 true true 0

sync.Map and sync.Pool

sync.Map suits keys written once and read many times, or goroutines touching disjoint keys; otherwise a map with a Mutex is simpler and typed. A Pool keeps temporary objects to reuse, and may drop them at any garbage collection.

var seen sync.Map
seen.Store("a", 1)
v, loaded := seen.LoadOrStore("a", 2)
fmt.Println(v, loaded)
bufPool := sync.Pool{New: func() any { return new(bytes.Buffer) }}
buf := bufPool.Get().(*bytes.Buffer)
buf.WriteString("reuse me")
fmt.Println(buf.Len())
buf.Reset()
bufPool.Put(buf)// Output:
// 1 true
// 8

The Race Detector

Find data races

The race detector finds two goroutines touching the same memory without synchronization while at least one writes. It only sees races that happen during the run, so run your tests with -race in CI.

go test -race ./...
go run -race .// Output:
// WARNING: DATA RACE
// Write at 0x00c000014108 by goroutine 8:
//   main.main.func1()
//       /app/main.go:12 +0x44
// Previous read at 0x00c000014108 by goroutine 7:
//   main.main.func1()
//       /app/main.go:12 +0x30

context

Cancellation and Deadlines

WithTimeout and ctx.Done

Pass ctx as the first parameter of anything that does I/O or may block, and always call cancel, usually with defer, to release the timer. Done is closed when the context is canceled or times out, and Err says which.

func slowWork(ctx context.Context) error {
    select {
    case <-time.After(time.Second):
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    defer cancel()
    err := slowWork(ctx)
    fmt.Println(err, errors.Is(err, context.DeadlineExceeded))
}// Output:
// context deadline exceeded true

Cancel a tree of work

Canceling a parent cancels every context derived from it, which is how one request's cancellation stops all its database queries and HTTP calls.

ctx, cancel := context.WithCancel(context.Background())
child, stop := context.WithTimeout(ctx, time.Hour)
defer stop()
cancel()
<-child.Done()
fmt.Println(ctx.Err(), child.Err())// Output:
// context canceled context canceled

Say why with a cause

Go 1.21+

ctx.Err() only says canceled or deadline exceeded; context.Cause returns the error you passed, which makes logs readable.

ctx, cancel := context.WithCancelCause(context.Background())
cancel(errors.New("user logged out"))
fmt.Println(ctx.Err())
fmt.Println(context.Cause(ctx))
tctx, tcancel := context.WithTimeoutCause(context.Background(), time.Millisecond, errors.New("payment API too slow"))
defer tcancel()
<-tctx.Done()
fmt.Println(tctx.Err(), "|", context.Cause(tctx))// Output:
// context canceled
// user logged out
// context deadline exceeded | payment API too slow

Values and Helpers

Request-scoped values with a private key type

An unexported key type means no other package can read or overwrite your value by accident. Keep context values for request data such as user, trace ID or deadline; pass real parameters as parameters.

package main

import (
    "context"
    "fmt"
)

type ctxKey struct{}

func WithUser(ctx context.Context, name string) context.Context {
    return context.WithValue(ctx, ctxKey{}, name)
}

func User(ctx context.Context) (string, bool) {
    name, ok := ctx.Value(ctxKey{}).(string)
    return name, ok
}

func main() {
    ctx := WithUser(context.Background(), "ann")
    fmt.Println(User(ctx))
    fmt.Println(User(context.Background()))
}// Output:
// ann true
//  false

AfterFunc and WithoutCancel

Go 1.21+

AfterFunc runs a function in its own goroutine once the context is done. WithoutCancel keeps the values but not the cancellation, for work such as audit logging that must finish after the request ends.

ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
context.AfterFunc(ctx, func() {
    fmt.Println("cleanup after cancel")
    close(done)
})
detached := context.WithoutCancel(ctx)
cancel()
<-done
fmt.Println(ctx.Err(), detached.Err())// Output:
// cleanup after cancel
// context canceled <nil>

Rules

DoDo not
Pass ctx as the first parameter, named ctxstore a context in a struct field
Use r.Context() in HTTP handlers and t.Context() in testscall context.Background() deep inside library code
Call cancel on every path, usually with deferpass a nil context: use context.TODO() while refactoring
Check ctx.Err() or select on ctx.Done() in long loopsuse context values for optional function parameters

Concurrency Patterns

Worker Pool

A fixed number of workers reading from one channel

Closing jobs ends the workers' range loops; a separate goroutine closes results once every worker is done, which ends the collecting loop. Results arrive in any order, hence the sort.

package main

import (
    "fmt"
    "slices"
    "sync"
)

func main() {
    jobs := make(chan int)
    results := make(chan int)
    var wg sync.WaitGroup
    for range 3 {
        wg.Go(func() {
            for n := range jobs {
                results <- n * n
            }
        })
    }
    go func() {
        for i := 1; i <= 5; i++ {
            jobs <- i
        }
        close(jobs)
    }()
    go func() {
        wg.Wait()
        close(results)
    }()
    var out []int
    for r := range results {
        out = append(out, r)
    }
    slices.Sort(out)
    fmt.Println(out)
}// Output:
// [1 4 9 16 25]

Pipeline stages connected by channels

Each stage owns and closes its output channel. For stages that can stop early, pass a context and select on ctx.Done() around every send so upstream goroutines do not leak.

package main

import "fmt"

func gen(nums ...int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for _, n := range nums {
            out <- n
        }
    }()
    return out
}

func square(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for n := range in {
            out <- n * n
        }
    }()
    return out
}

func main() {
    for v := range square(square(gen(1, 2, 3))) {
        fmt.Print(v, " ")
    }
    fmt.Println()
}// Output:
// 1 16 81 

Limiting Concurrency

A buffered channel as a semaphore

At most cap(sem) goroutines hold a slot. errgroup.SetLimit and golang.org/x/sync/semaphore do the same with error handling and weights.

sem := make(chan struct{}, 2)
var running, peak atomic.Int32
var wg sync.WaitGroup
for range 6 {
    wg.Go(func() {
        sem <- struct{}{}
        defer func() { <-sem }()
        n := running.Add(1)
        for {
            p := peak.Load()
            if n <= p || peak.CompareAndSwap(p, n) {
                break
            }
        }
        time.Sleep(10 * time.Millisecond)
        running.Add(-1)
    })
}
wg.Wait()
fmt.Println("most at once:", peak.Load())// Output:
// most at once: 2

Fan-in: merge several channels

func merge[T any](chans ...<-chan T) <-chan T {
    out := make(chan T)
    var wg sync.WaitGroup
    for _, c := range chans {
        wg.Go(func() {
            for v := range c {
                out <- v
            }
        })
    }
    go func() { wg.Wait(); close(out) }()
    return out
}

func main() {
    a, b := make(chan string, 2), make(chan string, 2)
    a <- "a1"
    a <- "a2"
    b <- "b1"
    close(a)
    close(b)
    var got []string
    for v := range merge(a, b) {
        got = append(got, v)
    }
    slices.Sort(got)
    fmt.Println(got)
}// Output:
// [a1 a2 b1]

Rate limit with a ticker

A ticker spaces out work evenly. For bursts plus an average rate, golang.org/x/time/rate implements a token bucket with Wait(ctx) and Allow().

tick := time.NewTicker(20 * time.Millisecond)
defer tick.Stop()
start := time.Now()
for i := range 3 {
    <-tick.C
    fmt.Println("request", i)
}
fmt.Println(time.Since(start) >= 60*time.Millisecond)// Output:
// request 0
// request 1
// request 2
// true

fmt & slog

Printf Verbs

The verbs you use every day

VerbPrintsExample output
%vdefault format{ann 31}
%+vstructs with field names{Name:ann Age:31}
%#vGo syntaxmain.User{Name:"ann", Age:31}
%Tthe typemain.User
%d %b %o %xinteger in base 10, 2, 8, 1642 101010 52 2a
%f %.2f %e %gfloat, fixed, exponent, compact3.141593 3.14 3.141593e+00 3.141592653589793
%s %qstring, quoted stringgopher "gopher"
%tbooltrue
%c %Urune, Unicode code pointG U+0047
%ppointer address0xc000012345
%wwrapped error, fmt.Errorf onlysame as %v when printed
%%a literal percent sign%

See them run

%v works for anything and is the safe default. go vet checks every Printf call for verbs that do not match their arguments, and the Printf checker in the toolbox above does the same in your browser.

type User struct {
    Name string
    Age  int
}

func main() {
    u := User{"ann", 31}
    fmt.Printf("%v | %+v | %#v | %T\n", u, u, u, u)
    fmt.Printf("%d %b %o %x %X %#x\n", 42, 42, 42, 255, 255, 255)
    fmt.Printf("%f %.2f %e %g %g\n", math.Pi, math.Pi, math.Pi, math.Pi, 1e21)
    fmt.Printf("%s %q %v %c %U\n", "go", "go", []string{"a", "b"}, 'G', 'G')
    fmt.Printf("%t %v %d\n", true, nil, []int{1, 2})
}// Output:
// {ann 31} | {Name:ann Age:31} | main.User{Name:"ann", Age:31} | main.User
// 42 101010 52 ff FF 0xff
// 3.141593 3.14 3.141593e+00 3.141592653589793 1e+21
// go "go" [a b] G U+0047
// true <nil> [1 2]

Width, precision and alignment

A number after % is the width, after a dot the precision; - aligns left and 0 pads with zeros. * takes the width from an argument, and [n] picks the argument by position.

fmt.Printf("[%8s][%-8s][%08.3f][%+d][%x]\n", "right", "left", 3.14159, 5, "hi")
fmt.Printf("[%*d][%-*d]\n", 5, 42, 5, 42)
fmt.Printf("%[2]s %[1]s %[2]s\n", "world", "hello")
fmt.Printf("%6.2f%%\n", 12.3456)// Output:
// [   right][left    ][0003.142][+5][6869]
// [   42][42   ]
// hello world hello
//  12.35%

Custom Formatting

String methods and tables with tabwriter

fmt calls String on any value that has it, also inside slices and structs. Do not call fmt.Sprint(m) inside m's own String method with %v: it recurses forever.

package main

import (
    "fmt"
    "os"
    "text/tabwriter"
)

type Money int64

func (m Money) String() string { return fmt.Sprintf("$%d.%02d", m/100, m%100) }

func main() {
    fmt.Println(Money(123456), []Money{5, 1999})
    w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
    fmt.Fprintln(w, "NAME\tQTY\tPRICE")
    fmt.Fprintln(w, "gopher plush\t2\t$19.99")
    fmt.Fprintln(w, "sticker\t10\t$1.50")
    w.Flush()
}// Output:
// $1234.56 [$0.05 $19.99]
// NAME          QTY  PRICE
// gopher plush  2    $19.99
// sticker       10   $1.50

Sprint, Sscan and Appendf

Sprint adds spaces only between operands that are not strings; Sprintln always does. Append functions (Go 1.19) write into an existing byte slice without allocating a string.

s := fmt.Sprint("a", 1, 2, "b")
line := fmt.Sprintln("a", 1)
var name string
var age int
n, err := fmt.Sscan("ann 31", &name, &age)
buf := fmt.Appendf(nil, "id=%d", 7)
fmt.Printf("%q %q %v %v %s %d %s\n", s, line, n, err, name, age, buf)// Output:
// "a1 2b" "a 1\n" 2 <nil> ann 31 id=7

Logging with slog

Go 1.21+

Structured logs as JSON

Go 1.21+

slog writes key-value records that log systems can index. With adds fields to every later record; Group nests them. The ReplaceAttr here only drops the time so the output is stable.

opts := &slog.HandlerOptions{
    Level: slog.LevelDebug,
    ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
        if a.Key == slog.TimeKey {
            return slog.Attr{}
        }
        return a
    },
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
logger.Info("order placed", "id", 1042, "total", 59.90)
reqLog := logger.With("request_id", "r-77")
reqLog.Warn("slow query", slog.Duration("took", 1500*time.Millisecond))
reqLog.Debug("cache", slog.Group("stats", "hits", 9, "misses", 1))// Output:
// {"level":"INFO","msg":"order placed","id":1042,"total":59.9}
// {"level":"WARN","msg":"slow query","request_id":"r-77","took":1500000000}
// {"level":"DEBUG","msg":"cache","request_id":"r-77","stats":{"hits":9,"misses":1}}

Text logs, levels and the default logger

Go 1.21+

SetDefault also redirects the old log package, so existing log.Printf calls end up in the same structured output. slog.NewMultiHandler (Go 1.26) sends each record to several handlers, for example text to the console and JSON to a file.

h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
    ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
        if a.Key == slog.TimeKey {
            return slog.Attr{}
        }
        return a
    },
})
slog.SetDefault(slog.New(h))
slog.Info("server started", "port", 8080)
slog.Debug("hidden at the default Info level")
log.Printf("the log package now goes through slog too")// Output:
// level=INFO msg="server started" port=8080
// level=INFO msg="the log package now goes through slog too"

Files, OS & Processes

Reading and Writing Files

Whole files at once

ReadFile and WriteFile fit files that comfortably fit in memory. 0o644 is the Unix permission: owner reads and writes, everyone else reads. Check missing files with errors.Is(err, fs.ErrNotExist).

dir, err := os.MkdirTemp("", "demo")
if err != nil {
    log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "notes.txt")
if err := os.WriteFile(path, []byte("line one\nline two\n"), 0o644); err != nil {
    log.Fatal(err)
}
data, err := os.ReadFile(path)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%d bytes: %q\n", len(data), data)
_, err = os.ReadFile(filepath.Join(dir, "missing.txt"))
fmt.Println(errors.Is(err, fs.ErrNotExist))// Output:
// 18 bytes: "line one\nline two\n"
// true

Line by line with bufio.Scanner

Replace the strings.Reader with an *os.File to read a file. The default maximum line is 64 KiB; for longer lines call sc.Buffer(make([]byte, 0, 1<<20), 1<<20) before scanning, or use bufio.Reader.ReadString.

r := strings.NewReader("alpha\nbeta\n\ngamma")
sc := bufio.NewScanner(r)
n := 0
for sc.Scan() {
    n++
    fmt.Printf("%d: %q\n", n, sc.Text())
}
if err := sc.Err(); err != nil {
    fmt.Println("read error:", err)
}// Output:
// 1: "alpha"
// 2: "beta"
// 3: ""
// 4: "gamma"

Streams: io.Reader, io.Writer and io.Copy

io.Copy moves data in 32 KiB chunks between any reader and writer, so a 10 GB file never has to fit in memory. LimitReader, MultiWriter, TeeReader and Pipe compose streams without copying.

var out bytes.Buffer
src := io.LimitReader(strings.NewReader("stream me, but not all of me"), 9)
n, err := io.Copy(&out, src)
fmt.Println(n, err, out.String())
h := sha256.New()
w := io.MultiWriter(os.Stdout, h)
fmt.Fprint(w, "hash me\n")
fmt.Printf("%x\n", h.Sum(nil)[:4])// Output:
// 9 <nil> stream me
// hash me
// 8f6eb3e2

Create, append and flush

A bufio.Writer batches small writes; forgetting Flush loses the tail of the output. For files you write, the error from Close can also report data that never reached the disk.

f, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
    return err
}
defer f.Close()
bw := bufio.NewWriter(f)
fmt.Fprintf(bw, "%s started\n", time.Now().Format(time.RFC3339))
return bw.Flush()

Paths and Directories

filepath and WalkDir

filepath uses the operating system's separator; package path is for URLs and slash separated paths. WalkDir is faster than the older Walk because it does not call Stat on every entry.

dir, _ := os.MkdirTemp("", "tree")
defer os.RemoveAll(dir)
for _, p := range []string{"a/x.go", "a/b/y.go", "c.txt"} {
    full := filepath.Join(dir, p)
    os.MkdirAll(filepath.Dir(full), 0o755)
    os.WriteFile(full, nil, 0o644)
}
filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
    if err == nil && filepath.Ext(path) == ".go" {
        rel, _ := filepath.Rel(dir, path)
        fmt.Println(filepath.ToSlash(rel), filepath.Base(path))
    }
    return err
})// Output:
// a/b/y.go y.go
// a/x.go x.go

os.Root stops path traversal

Go 1.25+

os.Root (Go 1.24) confines every operation to one directory, including through symlinks, so a user supplied name such as ../../etc/passwd cannot escape. Root.WriteFile and friends arrived in Go 1.25.

dir, _ := os.MkdirTemp("", "uploads")
defer os.RemoveAll(dir)
root, err := os.OpenRoot(dir)
if err != nil {
    log.Fatal(err)
}
defer root.Close()
fmt.Println(root.WriteFile("ok.txt", []byte("fine"), 0o644))
_, err = root.Open("../../etc/passwd")
fmt.Println(err)// Output:
// <nil>
// openat ../../etc/passwd: path escapes from parent

Embed files in the binary

//go:embed must sit right above a package level variable of type string, []byte or embed.FS. The files are compiled into the binary, so a single file deploy carries its templates and assets.

import (
    "embed"
    "net/http"
)

//go:embed templates/*.html static

var assets embed.FS

//go:embed version.txt

var version string

func main() {
    page, _ := assets.ReadFile("templates/index.html")
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write(page) })
    http.Handle("/static/", http.FileServerFS(assets))
}

Arguments, Environment and Commands

Flags with the flag package

In a real program call flag.Parse() and read flag.Args(); here a FlagSet parses a fixed list so the output is repeatable. Flags stop at the first argument that is not a flag. -h prints the usage text built from the descriptions.

set := flag.NewFlagSet("server", flag.ContinueOnError)
port := set.Int("port", 8080, "port to listen on")
verbose := set.Bool("v", false, "verbose logging")
var name string
set.StringVar(&name, "name", "api", "service name")
err := set.Parse([]string{"-port", "9090", "-v", "input.csv", "extra"})
fmt.Println(err, *port, *verbose, name, set.Args())// Output:
// <nil> 9090 true api [input.csv extra]

Environment variables

Getenv returns "" for both unset and empty; LookupEnv tells them apart. cmp.Or(os.Getenv("PORT"), "8080") is a short way to apply a default.

os.Setenv("APP_MODE", "prod")
mode := os.Getenv("APP_MODE")
_, set := os.LookupEnv("NOT_SET_ANYWHERE")
port := cmp.Or(os.Getenv("PORT"), "8080")
fmt.Println(mode, set, port, len(os.Args) > 0)// Output:
// prod false 8080 true

Run a command

exec.Command runs the program directly, not through a shell, so arguments are never split or expanded, which prevents shell injection. Pass user input as separate arguments, never inside a sh -c string.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--short", "HEAD")
out, err := cmd.Output()
if err != nil {
    var ee *exec.ExitError
    if errors.As(err, &ee) {
        log.Printf("git failed: %s", ee.Stderr)
    }
    return err
}
fmt.Println(strings.TrimSpace(string(out)))

Stop cleanly on Ctrl+C

NotifyContext cancels the context on the first signal. Since Go 1.26 context.Cause reports which signal it was. A second Ctrl+C after stop() ends the program immediately.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go runServer(ctx)
<-ctx.Done()
log.Println("shutting down:", context.Cause(ctx))

JSON

Marshal and Unmarshal

Struct tags control the names

Only exported fields are encoded; json:"-" skips one. omitempty drops zero numbers, empty strings, nil or empty slices and maps; omitzero (Go 1.24) drops zero values including structs such as time.Time, which omitempty never omits. Map keys come out sorted.

type Item struct {
    SKU      string    `json:"sku"`
    Price    float64   `json:"price"`
    Tags     []string  `json:"tags,omitempty"`
    Internal string    `json:"-"`
    Added    time.Time `json:"added,omitzero"`
    note     string
}

func main() {
    b, err := json.Marshal(Item{SKU: "g-1", Price: 9.5, Internal: "x", note: "y"})
    fmt.Println(string(b), err)
    pretty, _ := json.MarshalIndent(map[string]int{"b": 2, "a": 1}, "", "  ")
    fmt.Println(string(pretty))
}// Output:
// {"sku":"g-1","price":9.5} <nil>
// {
//   "a": 1,
//   "b": 2
// }

Decode into a struct

encoding/json matches names case-insensitively and ignores unknown fields. A type mismatch returns an *UnmarshalTypeError that names the field. Pass a pointer, or Unmarshal returns an error.

type Order struct {
    ID    int      `json:"id"`
    Items []string `json:"items"`
    Paid  bool     `json:"paid"`
}

func main() {
    var o Order
    err := json.Unmarshal([]byte(`{"id": 7, "ITEMS": ["a", "b"], "extra": true}`), &o)
    fmt.Printf("%+v %v\n", o, err)
    err = json.Unmarshal([]byte(`{"id": "seven"}`), &o)
    fmt.Println(err)
}// Output:
// {ID:7 Items:[a b] Paid:false} <nil>
// json: cannot unmarshal string into Go struct field Order.id of type int

Unknown shape: map[string]any

Every JSON number becomes float64 in an any, which loses precision above 2^53. UseNumber keeps the digits as a json.Number string. For known shapes, define structs: the JSON to Go struct tool above writes them.

var v map[string]any
json.Unmarshal([]byte(`{"n": 42, "list": [1, "two"], "obj": {"ok": true}}`), &v)
fmt.Printf("%T %v | %T | %v\n", v["n"], v["n"], v["list"], v["obj"].(map[string]any)["ok"])
d := json.NewDecoder(strings.NewReader(`{"id": 12345678901234567890}`))
d.UseNumber()
var w map[string]any
d.Decode(&w)
fmt.Println(w["id"])// Output:
// float64 42 | []interface {} | true
// 12345678901234567890

nil slices become null

In encoding/json a nil slice encodes as null and an empty one as []. APIs whose clients expect an array should initialize the slice, or use encoding/json/v2, where both encode as [].

type Resp struct {
    Items []string `json:"items"`
}
var a, b Resp
b.Items = []string{}
x, _ := json.Marshal(a)
y, _ := json.Marshal(b)
fmt.Println(string(x), string(y))// Output:
// {"items":null} {"items":[]}

Streaming and Custom Types

Encoder and Decoder for streams

Decoder reads one value at a time from any io.Reader, such as an HTTP body; Encoder writes each value followed by a newline. DisallowUnknownFields turns silently ignored fields into errors.

in := strings.NewReader(`{"n":1} {"n":2} {"n":3}`)
dec := json.NewDecoder(in)
dec.DisallowUnknownFields()
enc := json.NewEncoder(os.Stdout)
for {
    var m struct{ N int }
    if err := dec.Decode(&m); err == io.EOF {
        break
    } else if err != nil {
        fmt.Println(err)
        break
    }
    m.N *= 10
    enc.Encode(m)
}// Output:
// {"N":10}
// {"N":20}
// {"N":30}

MarshalJSON and UnmarshalJSON

MarshalJSON on the value type and UnmarshalJSON on the pointer type is the usual pairing. For plain text formats, MarshalText and UnmarshalText are simpler and also work for map keys.

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type Level int

func (l Level) MarshalJSON() ([]byte, error) {
    return json.Marshal([]string{"low", "high"}[l])
}

func (l *Level) UnmarshalJSON(b []byte) error {
    var s string
    if err := json.Unmarshal(b, &s); err != nil {
        return err
    }
    if strings.EqualFold(s, "high") {
        *l = 1
    } else {
        *l = 0
    }
    return nil
}

func main() {
    b, _ := json.Marshal(map[string]Level{"alert": 1})
    var back map[string]Level
    err := json.Unmarshal([]byte(`{"x": "HIGH"}`), &back)
    fmt.Println(string(b), back["x"], err)
}// Output:
// {"alert":"high"} 1 <nil>

encoding/json/v2

Go 1.27+

Stricter defaults

Go 1.27+

encoding/json/v2 became a standard package in Go 1.27: nil slices and maps encode as [] and {}, duplicate names and invalid UTF-8 are errors, and names match case-sensitively unless you ask. encoding/json itself now runs on the v2 engine with its old behavior, and unmarshals faster.

type T struct {
    Name string
    Tags []string
}

func main() {
    v2, _ := jsonv2.Marshal(T{Name: "x"})
    fmt.Println(string(v2))
    var t T
    fmt.Println(jsonv2.Unmarshal([]byte(`{"Name":"a","Name":"b"}`), &t))
    var u T
    fmt.Println(jsonv2.Unmarshal([]byte(`{"name":"lower"}`), &u), u.Name == "")
    fmt.Println(jsonv2.Unmarshal([]byte(`{"name":"lower"}`), &u, jsonv2.MatchCaseInsensitiveNames(true)), u.Name)
}// Output:
// {"Name":"x","Tags":[]}
// jsontext: duplicate object member name "Name"
// <nil> true
// <nil> lower

Tokens with jsontext

Go 1.27+

jsontext reads and writes JSON as tokens, with a state machine that guarantees the sequence is valid JSON. It suits very large documents and proxies that rewrite JSON without decoding it into Go values.

dec := jsontext.NewDecoder(strings.NewReader(`{"a": [1, 2], "b": null}`))
for {
    tok, err := dec.ReadToken()
    if err != nil {
        break
    }
    fmt.Print(tok.Kind(), " ")
}
fmt.Println()// Output:
// { string [ number number ] string null } 

net/http

Server and Routing

Method and path patterns

Go 1.22+

Since Go 1.22 ServeMux matches methods and {wildcards}; a wrong method gets 405 with an Allow header. {path...} matches the rest of the path. Here httptest calls the router directly; a real server passes mux to http.Server.

mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "user %s", r.PathValue("id"))
})
mux.HandleFunc("POST /users", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusCreated)
})
mux.HandleFunc("GET /files/{path...}", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "file ", r.PathValue("path"))
})
for _, t := range [][2]string{{"GET", "/users/42"}, {"POST", "/users"}, {"DELETE", "/users/42"}, {"GET", "/files/a/b.txt"}} {
    rec := httptest.NewRecorder()
    mux.ServeHTTP(rec, httptest.NewRequest(t[0], t[1], nil))
    fmt.Println(t[0], t[1], rec.Code, rec.Body.String())
}// Output:
// GET /users/42 200 user 42
// POST /users 201 
// DELETE /users/42 405 Method Not Allowed
//
// GET /files/a/b.txt 200 file a/b.txt

A JSON endpoint

Set headers before WriteHeader, and WriteHeader before the body; the first Write sends 200 if you did not. MaxBytesReader caps the body so a client cannot exhaust memory.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
)

type CreateReq struct {
    Name string `json:"name"`
}

func create(w http.ResponseWriter, r *http.Request) {
    var req CreateReq
    r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" {
        http.Error(w, "name is required", http.StatusBadRequest)
        return
    }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": req.Name})
}

func main() {
    for _, body := range []string{`{"name":"ann"}`, `{}`} {
        rec := httptest.NewRecorder()
        create(rec, httptest.NewRequest("POST", "/users", strings.NewReader(body)))
        fmt.Print(rec.Code, " ", rec.Body.String())
    }
}// Output:
// 201 {"id":1,"name":"ann"}
// 400 name is required

Middleware wraps a handler

Middleware is a function from Handler to Handler, so logging, auth, recovery and CORS stack by nesting calls. Put request scoped values in r.Context() with r.WithContext.

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
)

func requireKey(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("X-API-Key") != "secret" {
            http.Error(w, "forbidden", http.StatusForbidden)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func main() {
    hello := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") })
    h := requireKey(hello)
    for _, key := range []string{"", "secret"} {
        req := httptest.NewRequest("GET", "/", nil)
        req.Header.Set("X-API-Key", key)
        rec := httptest.NewRecorder()
        h.ServeHTTP(rec, req)
        fmt.Printf("%d %q\n", rec.Code, rec.Body.String())
    }
}// Output:
// 403 "forbidden\n"
// 200 "hello"

Production Server

Timeouts and graceful shutdown

http.ListenAndServe with no Server sets no timeouts, so slow clients can hold connections forever. Shutdown stops accepting new connections and waits for active requests up to the deadline.

srv := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       30 * time.Second,
    WriteTimeout:      30 * time.Second,
    IdleTimeout:       2 * time.Minute,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
    if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
        log.Fatal(err)
    }
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)

CSRF protection without tokens

Go 1.25+

CrossOriginProtection (Go 1.25) rejects cross-origin unsafe requests using the Sec-Fetch-Site and Origin headers that modern browsers send, which removes the need for CSRF tokens in most apps.

csrf := http.NewCrossOriginProtection()
csrf.AddTrustedOrigin("https://admin.example.com")
handler := csrf.Handler(mux)

HTTP Client

A client with a timeout and a context

http.Get uses a client with no timeout. Always close the body, check StatusCode yourself (a 404 or 500 is not an error to Do), and reuse one Client: it keeps connections open between requests.

client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.example.com/items?page=2", nil)
if err != nil {
    return err
}
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
    return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
    return fmt.Errorf("unexpected status %s", resp.Status)
}
var items []Item
return json.NewDecoder(resp.Body).Decode(&items)

Build URLs safely

Never build query strings by concatenation: Encode escapes values and sorts keys. URL.Clone and Values.Clone (Go 1.27) make deep copies before you modify a shared URL.

u, _ := url.Parse("https://api.example.com/search")
q := u.Query()
q.Set("q", "go & rust")
q.Set("page", "2")
u.RawQuery = q.Encode()
fmt.Println(u.String())
fmt.Println(url.PathEscape("a b/c"), url.QueryEscape("a b/c"))// Output:
// https://api.example.com/search?page=2&q=go+%26+rust
// a%20b%2Fc a+b%2Fc

Time & Dates

Formatting and Parsing

Layouts use the reference time Mon Jan 2 15:04:05 MST 2006

The layout is the reference time written the way you want the output: 01 month, 02 day, 15 hour, 04 minute, 05 second, 2006 year, or 1 2 3 4 5 6 in order. The time layout tool in the toolbox converts %Y-%m-%d and yyyy-MM-dd patterns.

t := time.Date(2026, time.September, 29, 14, 5, 9, 0, time.UTC)
fmt.Println(t.Format("2006-01-02 15:04:05"))
fmt.Println(t.Format("Jan 2, 2006 at 3:04pm"))
fmt.Println(t.Format(time.RFC3339), t.Format(time.DateOnly), t.Format(time.Kitchen))
fmt.Println(t.Format("Monday 02/01/06 _2 002"))// Output:
// 2026-09-29 14:05:09
// Sep 29, 2026 at 2:05pm
// 2026-09-29T14:05:09Z 2026-09-29 2:05PM
// Tuesday 29/09/26 29 272

Parse with a layout

Parse without a zone in the layout returns UTC; ParseInLocation interprets the text in the given zone. Add import _ "time/tzdata" to embed the zone database (about 450 KB) when the target has none, such as scratch containers or Windows.

t, err := time.Parse("2006-01-02 15:04", "2026-09-29 18:30")
fmt.Println(t, err)
_, err = time.Parse(time.DateOnly, "2026-13-01")
fmt.Println(err)
loc, _ := time.LoadLocation("Europe/Bucharest")
local, _ := time.ParseInLocation(time.DateTime, "2026-09-29 18:30:00", loc)
fmt.Println(local, local.UTC())// Output:
// 2026-09-29 18:30:00 +0000 UTC <nil>
// parsing time "2026-13-01": month out of range
// 2026-09-29 18:30:00 +0300 EEST 2026-09-29 15:30:00 +0000 UTC

The layout tokens

TokenMeaningTokenMeaning
2006 06year15 03 3hour, 24h or 12h
01 1 Jan Januarymonth04 4minute
02 2 _2day of month05 5second
002day of year.000 .999fraction, fixed or trimmed
Mon MondayweekdayPM pmAM/PM marker
MSTzone name-0700 -07:00 Z07:00zone offset

Durations and Arithmetic

time.Duration is nanoseconds

Multiplying by an untyped constant works directly, but an int variable must be converted: time.Duration(n) * time.Second. time.Sleep(5) sleeps 5 nanoseconds, a classic bug.

d := 90*time.Minute + 30*time.Second
fmt.Println(d, d.Hours(), d.Round(time.Hour), d.Truncate(time.Hour))
p, _ := time.ParseDuration("1h15m30.5s")
fmt.Println(p, p.Seconds())
n := 3
fmt.Println(time.Duration(n) * time.Second)// Output:
// 1h30m30s 1.5083333333333333 2h0m0s 1h0m0s
// 1h15m30.5s 4530.5
// 3s

Add, compare and difference

AddDate normalizes overflow, so January 31 plus one month is March 3. Compare times with Equal, Before and After, not ==, which also compares the location and monotonic reading.

start := time.Date(2026, 1, 31, 9, 0, 0, 0, time.UTC)
fmt.Println(start.Add(36*time.Hour), start.AddDate(0, 1, 0))
end := start.Add(90 * time.Minute)
fmt.Println(end.Sub(start), end.After(start), start.Equal(start.In(time.Local)))
fmt.Println(start.Weekday(), start.YearDay(), start.Unix(), time.Unix(0, 0).UTC())// Output:
// 2026-02-01 21:00:00 +0000 UTC 2026-03-03 09:00:00 +0000 UTC
// 1h30m0s true true
// Saturday 31 1769850000 1970-01-01 00:00:00 +0000 UTC

Timers and Tickers

Timer, AfterFunc and Ticker

Since Go 1.23 timer channels are unbuffered, so Stop and Reset never leave a stale value behind, and unstopped timers and tickers are garbage collected. Go 1.27 removed the asynctimerchan setting that restored the old behavior.

timer := time.NewTimer(50 * time.Millisecond)
stopped := timer.Stop()
fmt.Println("stopped before firing:", stopped)
done := make(chan bool)
time.AfterFunc(10*time.Millisecond, func() { done <- true })
fmt.Println("AfterFunc ran:", <-done)
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for i := range 3 {
    <-ticker.C
    fmt.Println("tick", i)
}// Output:
// stopped before firing: true
// AfterFunc ran: true
// tick 0
// tick 1
// tick 2

Wall clock and monotonic clock

time.Now carries a monotonic reading, so Since and Sub measure elapsed time correctly even if the system clock jumps. Round(0) strips it, for example before comparing with ==.

start := time.Now()
time.Sleep(20 * time.Millisecond)
elapsed := time.Since(start)
fmt.Println(elapsed >= 20*time.Millisecond, strings.Contains(start.String(), "m=+"))
fmt.Println(strings.Contains(start.Round(0).String(), "m=+"))// Output:
// true true
// false

Modules & Workspaces

go.mod and Dependencies

A typical go.mod

The go line is the minimum Go version and turns on that version's language features; toolchain names the preferred release. go.sum stores checksums of every module you depend on: commit both files. The read go.mod tool above explains any go.mod you paste.

module github.com/acme/shop

go 1.27.0

toolchain go1.27.1

require (
    github.com/jackc/pgx/v5 v5.11.0
    golang.org/x/sync v0.23.0
)

require golang.org/x/text v0.42.0 // indirect


tool golang.org/x/tools/cmd/stringer

Add, upgrade and remove dependencies

Go picks the minimum version that satisfies every requirement (minimal version selection), so builds do not change just because a new release came out. Run go mod tidy before committing.

go get github.com/jackc/pgx/v5            # add or upgrade to the latest release

go get github.com/jackc/pgx/v5@v5.11.0     # a specific version

go get golang.org/x/sync@none             # remove it

go get -u ./...                           # upgrade every dependency, minor and patch

go get -u=patch ./...                     # patch releases only

go mod tidy                               # add what is imported, drop what is not

go list -m -u all                         # which modules have updates

go mod why -m golang.org/x/text           # why is this module needed

Major versions live in the import path

From v2 on, a module's path ends in /vN, so v1 and v2 can be used side by side. A tag such as v2.3.0 on a module without /v2 in its path shows up as +incompatible.

import (
    "github.com/jackc/pgx/v5"
    "gopkg.in/yaml.v3"
)

Local Development

replace and workspaces

Go 1.18+

A replace pointing at a local directory is for development: it breaks go install for others. A go.work file does the same for your machine only and usually stays out of version control.

go mod edit -replace github.com/acme/lib=../lib   # this module only

go mod edit -dropreplace github.com/acme/lib

go work init ./shop ./lib                        # go.work: several modules at once

go work use ./tools
go work sync

Tool dependencies

Go 1.24+

Since Go 1.24 go.mod records tools with a tool directive, versioned and checksummed like any dependency, replacing the old tools.go file with blank imports.

go get -tool golang.org/x/tools/cmd/stringer@latest
go tool stringer -type=Color
go get -tool honnef.co/go/tools/cmd/staticcheck@2026.2.1
go tool staticcheck ./...
go get -u tool                                   # upgrade all tools

Private modules and proxies

GOPRIVATE skips the public proxy and checksum database for matching paths, so private code never leaves your network. GOAUTH (Go 1.24) supplies credentials for private module servers.

go env -w GOPRIVATE=github.com/acme/*,gitlab.corp.example.com
go env -w GOPROXY=https://proxy.golang.org,direct

git config --global url."git@github.com:acme/".insteadOf "https://github.com/acme/"
GOFLAGS=-mod=mod go build ./...
go mod vendor                                    # copy dependencies into vendor/

Versions in Code

Compare Go versions with go/version

Go 1.22+

go/version (Go 1.22) compares Go release strings correctly, including release candidates, which plain string comparison gets wrong for go1.9 versus go1.10. Tools use it to decide which language features a go line allows.

fmt.Println(version.Compare("go1.26.8", "go1.27.1"), version.Compare("go1.27", "go1.27.0"))
fmt.Println(version.Lang("go1.27.1"), version.IsValid("go1.27rc1"), version.IsValid("1.27"))// Output:
// -1 -1
// go1.27 true false

Testing & Benchmarks

Unit Tests

A table driven test

Tests live in files ending in _test.go, in functions named TestXxx(t *testing.T). Errorf records a failure and continues; Fatalf stops this test. t.Run gives each case a name you can select with -run 'TestAbs/negative'.

package mathx

import "testing"

func TestAbs(t *testing.T) {
    tests := []struct {
        name string
        in   int
        want int
    }{
        {"positive", 3, 3},
        {"negative", -3, 3},
        {"zero", 0, 0},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Abs(tt.in); got != tt.want {
                t.Errorf("Abs(%d) = %d, want %d", tt.in, got, tt.want)
            }
        })
    }
}

Run them

A failing subtest prints --- FAIL: TestAbs/negative with the file, line and message from Errorf. Results are cached when neither the code nor the test inputs changed; -count=1 forces a real run. The go test builder above writes these commands for coverage, benchmarks and fuzzing.

go test ./...
go test -v -run 'TestAbs/negative' ./mathx
go test -race -count=1 ./...
go test -cover ./...

Helpers, cleanup, temp dirs and the test context

Go 1.24+

t.Helper makes failures point at the caller's line. TempDir is removed after the test, Setenv is restored, and t.Context (Go 1.24) is canceled just before Cleanup functions run.

func newStore(t *testing.T) *Store {
    t.Helper()
    dir := t.TempDir()
    t.Setenv("STORE_MODE", "test")
    s, err := Open(t.Context(), filepath.Join(dir, "db"))
    if err != nil {
        t.Fatalf("open store: %v", err)
    }
    t.Cleanup(func() { s.Close() })
    return s
}

Test HTTP handlers with httptest

NewRecorder calls a handler with no network at all. httptest.NewServer starts a real server on a loopback port for client code; Go 1.27's NewTestServer runs one in memory for use with synctest.

func TestHealth(t *testing.T) {
    rec := httptest.NewRecorder()
    req := httptest.NewRequest(http.MethodGet, "/health", nil)
    healthHandler(rec, req)
    if rec.Code != http.StatusOK {
        t.Fatalf("status = %d, want 200", rec.Code)
    }
}

Benchmarks, Fuzzing and Examples

Benchmarks with b.Loop

Go 1.24+

Each result line shows the benchmark name with GOMAXPROCS, the iteration count, ns/op, and with -benchmem B/op and allocs/op. b.Loop (Go 1.24) times only the loop, runs setup once, and keeps the compiler from optimizing the call away. Compare runs with benchstat instead of eyeballing single numbers.

func BenchmarkJoin(b *testing.B) {
    parts := []string{"a", "b", "c", "d"}
    for b.Loop() {
        strings.Join(parts, ",")
    }
}

go test -run='^$' -bench=Join -benchmem ./...

Fuzz tests find inputs you did not think of

Go 1.18+

The fuzzer mutates the seed inputs and keeps any input that finds new code paths. A failing input is saved under testdata/fuzz and becomes a regular test case from then on.

func FuzzReverse(f *testing.F) {
    f.Add("hello")
    f.Fuzz(func(t *testing.T, s string) {
        r := Reverse(Reverse(s))
        if utf8.ValidString(s) && r != s {
            t.Errorf("Reverse twice changed %q to %q", s, r)
        }
    })
}

go test -fuzz=FuzzReverse -fuzztime=30s ./strx

Examples are tests and documentation

go test runs ExampleXxx functions and compares what they print with the Output comment; go doc and pkg.go.dev show them next to the function they belong to.

func ExampleAbs() {
    fmt.Println(Abs(-5))
    // Output: 5

}

Fake time with testing/synctest

Go 1.27+

Inside synctest.Test (Go 1.25) time only moves when every goroutine in the bubble is blocked, so an hour of timeouts runs in microseconds and without flakes. synctest.Sleep (Go 1.27) sleeps and then waits for the other goroutines to settle.

func TestTimeout(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ctx, cancel := context.WithTimeout(t.Context(), time.Hour)
        defer cancel()
        synctest.Sleep(time.Hour)
        if ctx.Err() == nil {
            t.Fatal("expected the hour-long timeout to fire")
        }
    })
}

Allocations

Count allocations without a benchmark run

testing.AllocsPerRun reports the average number of heap allocations per call, a stable number that is ideal for tests that guard against regressions: if allocs := testing.AllocsPerRun(...); allocs > 1 { t.Fatal(...) }.

parts := []string{"a", "b", "c", "d", "e", "f", "g", "h"}
plus := testing.AllocsPerRun(100, func() {
    s := ""
    for _, p := range parts {
        s += p
    }
    _ = s
})
builder := testing.AllocsPerRun(100, func() {
    var b strings.Builder
    b.Grow(16)
    for _, p := range parts {
        b.WriteString(p)
    }
    _ = b.String()
})
fmt.Println("with +:", plus, "with Builder:", builder)// Output:
// with +: 7 with Builder: 1

Tools & Profiling

Formatting and Static Checks

The standard toolchain checks

go fix became the home of the modernizers in Go 1.26: it rewrites code to newer idioms that match your go line. Go 1.27 added atomictypes, embedlit, slicesbackward and unsafefuncs. The lint tool above flags the same patterns before you run it.

gofmt -l -w .                 # format files in place, list changed ones

go vet ./...                  # printf, copylocks, loopclosure, structtag and more

go fix ./...                  # apply modernizers: any, min/max, range over int, ...

go fix -diff ./...            # preview instead of writing

Linters and vulnerability scanning

third-party module

govulncheck only reports vulnerabilities in functions your code actually reaches, which keeps the list short. The GitHub Actions builder above wires vet, a linter, tests and govulncheck into CI.

go install honnef.co/go/tools/cmd/staticcheck@2026.2.1
staticcheck ./...
golangci-lint run ./...       # many linters in one run, configured in .golangci.yml

go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...

Inline a deprecated function for callers

Go 1.26+

With this directive, go fix replaces calls to OldName with its body, so library authors can deprecate an API and have their users' code updated automatically.

//go:fix inline

func OldName(s string) string { return NewName(s) }

Profiling

CPU and memory profiles

The pprof web UI opens on a flame graph since Go 1.26. Keep the pprof server on localhost or an internal port. Go 1.27 adds a goroutineleak profile at /debug/pprof/goroutineleak. The profiling builder above writes these commands.

import _ "net/http/pprof"

go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()

go tool pprof -http=:8081 "http://localhost:6060/debug/pprof/profile?seconds=30"
go tool pprof -http=:8081 http://localhost:6060/debug/pprof/heap

go test -run='^$' -bench=. -cpuprofile=cpu.out ./parser

Execution traces and the flight recorder

Go 1.25+

A trace shows every goroutine, syscall and GC pause over time. The flight recorder (Go 1.25) keeps the last few seconds in memory, so you can save a trace right after something rare and slow happens.

fr := trace.NewFlightRecorder(trace.FlightRecorderConfig{MinAge: 5 * time.Second})
fr.Start()
defer fr.Stop()
if slowRequest {
    f, _ := os.Create("slow.trace")
    fr.WriteTo(f)
    f.Close()
}

go tool trace slow.trace

Debug with Delve

third-party module

Delve understands goroutines, interfaces and maps, unlike gdb. Build with -gcflags=all="-N -l" when attaching to a binary, so variables are not optimized away.

go install github.com/go-delve/delve/cmd/dlv@latest
dlv debug ./cmd/api -- -port 8080
(dlv) break orders.go:42
(dlv) continue
(dlv) print order.Total
(dlv) goroutines

Builds

Build constraints and file names

A //go:build line before the package clause decides whether the file is compiled; it needs a blank line after it. File names ending in _linux.go, _windows_amd64.go or _test.go apply the same rules without a comment. Pass custom tags with go build -tags=prod.

//go:build linux && !cgo


package netx

Cross compile and stamp a version

The Go toolchain cross compiles to every supported target with no extra setup when cgo is off. go version -m prints the module versions and VCS revision embedded in any Go binary, which debug.ReadBuildInfo reads at run time.

GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o bin/api ./cmd/api
GOOS=windows GOARCH=amd64 go build -o bin/api.exe ./cmd/api
go build -ldflags="-s -w -X main.version=1.4.0" ./cmd/api
go version -m bin/api
go tool dist list | grep linux

Profile guided optimization

Go 1.21+

A CPU profile saved as default.pgo in the main package directory is used automatically (-pgo=auto is the default since Go 1.21), usually giving 2 to 14 percent faster code by inlining and devirtualizing the hot paths.

curl -o cmd/api/default.pgo "http://localhost:6060/debug/pprof/profile?seconds=60"
go build ./cmd/api

Go Tools as Libraries

What gofmt does, from code

go/format is the gofmt engine: tabs for indentation, spaces for alignment, one canonical layout, so formatting never comes up in code review. The go/ast, go/parser and go/types packages power linters and code generators the same way.

src := []byte("package main\nimport \"fmt\"\nfunc main(){fmt.Println( \"hi\" )\nx:=[]int{1,2,\n3}\n_=x}")
out, err := format.Source(src)
fmt.Println(string(out), err)// Output:
// package main
//
// import "fmt"
//
// func main() {
// 	fmt.Println("hi")
// 	x := []int{1, 2,
// 		3}
// 	_ = x
// }
//  <nil>

Evaluate a build constraint

This is how the go command decides whether a file is part of the build. go list -f '{{.GoFiles}}' shows the result for your own packages, and GOOS=windows go list does it for another target.

expr, err := constraint.Parse("//go:build linux && (amd64 || arm64) && !cgo")
if err != nil {
    log.Fatal(err)
}
for _, tags := range [][]string{{"linux", "arm64"}, {"linux", "amd64", "cgo"}, {"darwin", "arm64"}} {
    has := map[string]bool{}
    for _, t := range tags {
        has[t] = true
    }
    fmt.Println(tags, expr.Eval(func(tag string) bool { return has[tag] }))
}// Output:
// [linux arm64] true
// [linux amd64 cgo] false
// [darwin arm64] false

Errors & Gotchas

Compiler Errors

The errors every Go beginner meets

Unused variables and imports are errors, not warnings, and so is mixing numeric types without a conversion. The compiler stops after 10 errors, so fix the first ones first.

package main

import (
    "fmt"
    "os"
)

func half(n int) int {
    if n > 0 {
        return n / 2
    }
}

func main() {
    count := 3
    var ratio float64 = 1.5
    fmt.Println(ratio * count)
    fmt.Println(totl)
}// Output:
// # command-line-arguments
// ./main.go:5:5: "os" imported and not used
// ./main.go:12:1: missing return
// ./main.go:17:17: invalid operation: ratio * count (mismatched types float64 and int)
// ./main.go:18:17: undefined: totl

What each message means

MessageUsual fix
declared and not used: xuse it, delete it, or assign to _ while drafting
"os" imported and not useddelete the import; goimports does it on save
missing returnadd a return at the end, or a panic for impossible paths
invalid operation: mismatched typesconvert explicitly: float64(n) * ratio
cannot use x (variable of type T) as U valueconvert, or implement the missing method
undefined: nametypo, unexported name from another package, or missing import
x declared and not used after := in ifthe := made a new variable: use = to assign
assignment mismatch: 2 variables but f returns 1 valuematch the number of results

Runtime Panics

Index out of range

Indexing past the length panics with the index and the length. Check with if i < len(s), and remember that s[len(s)] is always out of range.

s := []int{1, 2, 3}
i := 5
fmt.Println(s[i])// Output:
// panic: runtime error: index out of range [5] with length 3
//
// goroutine 1 [running]:

Failed type assertion

Use the two-value form n, ok := v.(int), or a type switch, whenever the dynamic type is not guaranteed.

var v any = "text"
n := v.(int)
fmt.Println(n)// Output:
// panic: interface conversion: interface {} is string, not int
//
// goroutine 1 [running]:

Close a channel twice

Only the sender closes, exactly once. With several senders, close from the goroutine that waits for all of them, or guard it with sync.Once.

ch := make(chan int)
close(ch)
close(ch)// Output:
// panic: close of closed channel
//
// goroutine 1 [running]:

Surprises

range gives you a copy

The value variable is a copy of the element, so changing it changes nothing. Index into the slice, or range over a slice of pointers.

type Item struct{ Qty int }
items := []Item{{1}, {2}}
for _, it := range items {
    it.Qty *= 10
}
fmt.Println(items)
for i := range items {
    items[i].Qty *= 10
}
fmt.Println(items)// Output:
// [{1} {2}]
// [{10} {20}]

:= in an inner scope hides err

The inner := declared a new err, so the named result stayed nil and the failure vanished. go vet's shadow analyzer, run through golangci-lint, reports this pattern.

func load() (err error) {
    if true {
        _, err := strconv.Atoi("bad")
        _ = err
    }
    return err
}

func main() {
    fmt.Println(load())
}// Output:
// <nil>

Unexported fields are invisible to encoding/json

encoding/json, encoding/xml, text/template and reflect-based libraries can only see exported fields. Capitalize the field and set the wire name with a tag: Name string `json:"name"`.

type user struct {
    name  string
    Email string
}
b, _ := json.Marshal(user{name: "ann", Email: "a@example.com"})
fmt.Println(string(b))// Output:
// {"Email":"a@example.com"}

A defer in a loop waits for the function

Every file stays open until the surrounding function returns, which can hit the open file limit. Move the loop body into its own function so each defer runs per iteration. The lint tool above flags this pattern.

for _, name := range files {
    f, err := os.Open(name)
    if err != nil {
        return err
    }
    defer f.Close()
    process(f)
}

Go 1.21 to 1.27

What Each Release Added

Language and library highlights

ReleaseDateHighlights
Go 1.27Aug 2026generic methods, promoted field names in struct literals, encoding/json/v2, uuid and crypto/mldsa packages, strings.CutLast, goroutineleak profile
Go 1.26Feb 2026new(expr), self-referential generic constraints, Green Tea GC by default, errors.AsType, go fix modernizers, crypto/hpke
Go 1.25Aug 2025sync.WaitGroup.Go, testing/synctest, container-aware GOMAXPROCS, trace flight recorder, http.CrossOriginProtection
Go 1.24Feb 2025generic type aliases, tool directives, testing.B.Loop, os.Root, weak pointers, runtime.AddCleanup, omitzero, Swiss table maps
Go 1.23Aug 2024range over functions, package iter, slices and maps iterator helpers, unique package, timer changes
Go 1.22Feb 2024per-iteration loop variables, range over int, ServeMux method and wildcard patterns, math/rand/v2
Go 1.21Aug 2023min, max and clear built-ins, log/slog, slices, maps and cmp packages, toolchain management, PGO by default

Check and upgrade

Raising the go line enables that release's language changes, such as per-iteration loop variables from 1.22, for your module only; dependencies keep the semantics of their own go line.

go version
go get go@1.27.1 toolchain@go1.27.1
go mod tidy
go fix ./...
go vet ./...

Release Cycle and Support

Two releases a year, two supported

FactDetail
Major releasesevery six months, in February and August
Supported releasesthe two most recent: Go 1.27 and Go 1.26 today
Minor releasessecurity and bug fixes, for example Go 1.27.1 on September 1, 2026
CompatibilityGo 1 programs keep compiling and running; behavior changes go behind GODEBUG settings tied to the go line
Next releaseGo 1.28, expected in February 2027

GODEBUG keeps old behavior while you migrate

A //go:debug line in the main package or a godebug block in go.mod pins specific behaviors. Go 1.27 removed several settings, such as asynctimerchan and gotypesalias; the go command now reports a go.mod that still sets them to old values.

//go:debug http2client=0

package main

godebug (
    default=go1.26
    tlsmlkem=0
)

What Is a Go Cheat Sheet

A Go cheat sheet is a compact reference to the syntax, types, standard library and tooling of the Go programming language, arranged so you find the right form of a slice operation, a select statement or a go test flag in seconds. People also search for a Golang cheat sheet: Golang is the common nickname that comes from the old golang.org domain, and it means the same language.

This Go cheat sheet covers 30 sections and 216 snippets for Go 1.21 through Go 1.27, the current release. Every snippet that needs a newer release names the Go version that added it, and the version picker next to the search box hides what your go line cannot build. Rows that need a golang.org/x or third-party module say so under their title. The output shown under the example programs is what they printed when compiled and run on Compiler Explorer, with the Go development toolchain for Go 1.27 features and Go 1.26 for the rest.

The toolbox at the top lints Go code for the classic mistakes, checks Printf verbs against their arguments like go vet, turns JSON into Go structs with tags, computes struct layout and padding for 64-bit and 32-bit targets, converts date formats into Go's reference time layouts, flags regular expression features that Go's RE2 engine does not have, and explains a go.mod file. The builders write go build commands for cross compiling, multi-stage Dockerfiles, go test commands, GitHub Actions workflows, and profiling and Delve sessions. Everything runs in your browser.

How It Differs From the Tour of Go

The Tour of Go teaches the language step by step; this page is for when you already write Go and need the exact form of something, next to the mistake that usually comes with it: the nil map write, the defer in a loop, the typed nil error, the slice that shares its backing array. It works best alongside the compiler, go vet and a linter such as staticcheck. For the systems language on the other side of the tradeoff, see the Rust cheat sheet; for the language Go borrowed its syntax from, the C cheat sheet.


What This Go Cheat Sheet Covers

The 30 sections go from installing Go to shipping and profiling a service, and each link jumps to that section above.


Go Syntax Quick Reference

The forms people look up most often, one line each. The sections above show each of them in a full example with its output.

TaskGo
Declare and assignname := "gopher"
Declare with a typevar count int64
Constant enumconst ( A = iota; B; C )
Function with an errorfunc load(id int) (*User, error)
Check an errorif err != nil { return fmt.Errorf("load: %w", err) }
Slice literalnums := []int{1, 2, 3}
Appendnums = append(nums, 4)
Map literalages := map[string]int{"ann": 31}
Map lookupv, ok := ages["bob"]
Loop n timesfor i := range n { }
Loop over a slicefor i, v := range nums { }
Struct typetype User struct { Name string `json:"name"` }
Methodfunc (u *User) Rename(n string) { u.Name = n }
Interfacetype Shape interface { Area() float64 }
Generic functionfunc Map[T, U any](xs []T, f func(T) U) []U
Type switchswitch v := x.(type) { case string: }
Start a goroutinego work(ch) or wg.Go(func() { work() })
Channelch := make(chan int, 10)
Wait with a timeoutselect { case v := <-ch: case <-ctx.Done(): }
Clean updefer f.Close()
Sort a sliceslices.Sort(nums)
Format a datet.Format("2006-01-02 15:04")
Encode JSONb, err := json.Marshal(v)
HTTP routemux.HandleFunc("GET /users/{id}", h)
Run the testsgo test -race ./...
Cross compileGOOS=linux GOARCH=arm64 go build ./cmd/app

What Go Is

Go is a statically typed, compiled, garbage collected programming language designed at Google by Robert Griesemer, Rob Pike and Ken Thompson, announced in 2009 and stable since Go 1.0 in 2012. It was built for large codebases and many engineers: fast compilation, one standard format, a small language with few ways to do each thing, and concurrency built into the language through goroutines and channels.

A new major release ships every six months, in February and August, and the two most recent are supported with security fixes. Go 1.27, released on August 19, 2026, is the current version, with Go 1.27.4 from November 10, 2026 as the latest patch release. The Go 1 compatibility promise means code written for Go 1.0 still compiles today.

Go is the language of cloud infrastructure: Docker, Kubernetes, Terraform, Prometheus and etcd are all written in it, which is why it pairs naturally with the Docker cheat sheet and the Kubernetes cheat sheet. It is just as common for back-end development: HTTP APIs, microservices, command line tools and network servers.

Where It Fits

Choose Go for network services, APIs, CLIs and infrastructure tools where you want a single static binary, quick builds, good performance and simple concurrency. It gives up some expressiveness for readability: there are no exceptions, no inheritance and few ways to write the same loop. Rust fits better when you need full control of memory without a garbage collector; Python is quicker for scripts and data work, and the Python cheat sheet covers it.


How a Go Program Is Built and Run

go build hides several steps, and knowing them explains most build errors and deployment questions.

  1. The go command reads go.mod, picks the toolchain and resolves every dependency to an exact version using minimal version selection, verified against go.sum.
  2. It builds packages in dependency order. Each package is compiled as a unit: unused imports and variables, type errors and missing methods are reported here.
  3. The compiler inlines small functions, runs escape analysis to decide what lives on the stack or the heap, and applies a CPU profile when default.pgo is present.
  4. The linker combines the packages and the Go runtime, which contains the scheduler and garbage collector, into one executable, statically linked unless cgo is used.
  5. At run time the scheduler multiplexes goroutines onto GOMAXPROCS operating system threads, and the garbage collector reclaims heap memory concurrently with the program.

Because the result is one file with no runtime to install, deploying Go is copying a binary or building a tiny container image, which the Dockerfile builder above writes for you. It fits any build pipeline with a single go build step.


Go, Rust and Python Compared

The differences that matter when choosing a language for a service or a tool.

QuestionGoRustPython
Memory managementgarbage collectorownership checked at compile timereference counting and GC
Concurrencygoroutines and channels in the languagethreads and async, checked for data racesasyncio, threads limited by the GIL unless free threaded
Error handlingerror values, if err != nilResult and the ? operatorexceptions
Genericstype parameters since 1.18generics and traitstype hints only
Build outputone static binary, fast buildsone binary, slower buildssource plus an interpreter
Learning curvesmall language, quick to learnsteepgentle

Many teams combine them: Go for the services, Python for data and scripts, Rust for the few components where every microsecond or byte counts.


Common Go Mistakes

The same handful of problems shows up in code reviews of most Go projects.

In Code

  • Writing to a nil map, which panics; reading from one is fine.
  • Ignoring an error, or wrapping it with %v instead of %w so errors.Is can no longer find it.
  • Returning a nil pointer of a concrete type as an error, which is not a nil interface.
  • Appending to a sub-slice and overwriting elements the caller still uses.
  • Starting goroutines with no way to stop them, and leaking them when nobody reads their channel.
  • Copying a struct that contains a sync.Mutex, usually through a value receiver.

In Builds and Services

  • Using http.Get or http.ListenAndServe, neither of which sets a timeout.
  • Not closing response bodies, which leaks connections.
  • Never running tests with -race, where data races would show up.
  • Forgetting that a go line below 1.22 keeps the old shared loop variable.
  • Committing a replace directive that points at a local directory.
  • Exposing /debug/pprof on a public port.

How to Learn Go Well

Start With Small Programs and the Standard Library

Take the Tour of Go, then write small command line tools and an HTTP API using only the standard library: net/http, encoding/json, database/sql and log/slog carry you a long way before a framework is needed. Write tests from the start, table driven, with go test -race, which suits a test-driven development habit. Keep your code in version control with the git cheat sheet.

Then Learn Concurrency and the Tools

Learn goroutines, channels and context with small programs you can run under the race detector, then read Effective Go and the standard library source, which is idiomatic Go written by the language's authors. Profile a real service with pprof, deploy it in a container, and wire go vet, a linter and govulncheck into CI with the GitHub Actions builder above. An editor with gopls, set up with the VS Code workflow cheat sheet, shows errors and fixes as you type.


How This Go Cheat Sheet Is Maintained

This page is written and maintained by Bogdan Sandu for TMS Outsource, a software development company. It was checked against the Go 1.25, Go 1.26 and Go 1.27 release notes and the Go 1.27.4 release on November 18, 2026, and the output of the example programs was produced by compiling and running them on Compiler Explorer. If a snippet is wrong or out of date, the date in the byline shows when it was last reviewed.


Go Programming Questions People Actually Ask

The questions developers search for most about Go and about this cheat sheet, answered in a few sentences each.

Is Go the same as Golang?

Yes. The language is called Go; Golang is a nickname that comes from its original website, golang.org, and it stuck because "go" alone is hard to search for. The official site is now go.dev, but both names refer to the same language and toolchain.

What is the latest version of Go?

Go 1.27, released on August 19, 2026, with Go 1.27.4 as the latest patch release. It added generic methods, promoted field names in struct literals, encoding/json/v2 as a standard package, the uuid and crypto/mldsa packages, and a goroutine leak profile. Go 1.27 and Go 1.26 are the two supported releases.

Is Go good for beginners?

Yes. Go has a small language specification, one standard code format, clear compiler errors and a strong standard library, so beginners spend their time on programming rather than on the language. Pointers and explicit error handling take some getting used to, but there are no classes, exceptions or inheritance hierarchies to learn first.

What is the difference between a slice and an array in Go?

An array has a fixed length that is part of its type, such as [3]int, and assigning it copies every element. A slice is a small header that points into an array, with a length and a capacity; it can grow with append, and copies of a slice share the same elements. Most Go code uses slices.

How do goroutines differ from threads?

A goroutine is a function running concurrently, managed by the Go runtime rather than the operating system. It starts with a stack of a few kilobytes that grows as needed, so a program can run hundreds of thousands of them; the scheduler multiplexes them onto a small number of OS threads, set by GOMAXPROCS.

How does error handling work in Go?

Functions that can fail return an error as their last result, and the caller checks it with if err != nil. Add context with fmt.Errorf and the %w verb, and inspect wrapped errors with errors.Is, errors.As or, since Go 1.26, errors.AsType. panic is reserved for bugs and impossible states, not for expected failures.

Does Go have generics?

Yes, since Go 1.18. Functions and types can take type parameters with constraints such as any, comparable and cmp.Ordered, and Go 1.24 added generic type aliases. Go 1.27 added generic methods, so a method can declare its own type parameters, although interface methods still cannot.

What is Go used for?

Mostly for back-end services, APIs, microservices, command line tools, DevOps and cloud infrastructure. Docker, Kubernetes, Terraform, Prometheus, Hugo and CockroachDB are written in Go, and companies use it for high traffic web services because it combines good performance, low memory use and simple deployment as a single binary.

Is this Go cheat sheet up to date?

Yes. It covers Go 1.21 to Go 1.27 and was checked against the Go 1.27.4 release and the release notes of Go 1.25, 1.26 and 1.27 on November 18, 2026. Every snippet that needs a newer release names the Go version that added it, the version picker hides what your go line cannot build, and the program output was produced by real runs.

Can I download this Go cheat sheet as a PDF?

Yes. The page has a print stylesheet, so your browser's print command with Save as PDF produces a clean copy: every output and explanation is included, and the search box, navigation and footer are left out. Run a search first to print only the snippets that are still visible.