Go Cheat Sheet
A searchable, printable Go reference — structs, slices, maps, interfaces, error wrapping, goroutines, channels, generics and the go CLI. Free.
Basics
10package main
import ("fmt"; "os")
x := 42
var s string
const MaxRetries = 3
const (A = iota; B; C)
a, b = b, a
_, err := doWork()
fmt.Println("hi"); fmt.Printf("%v\n", x)
fmt.Sprintf("%s-%d", name, id)
Types, structs & methods
10type User struct { Name string; Age int }
u := User{Name: "Sam", Age: 30}
u.Name = "Alex"
func (u User) Label() string
func (u *User) Rename(n string)
func NewUser(n string) *User
type Admin struct { User; Level int }
type UserID int
Name string `json:"name,omitempty"`
p := &User{}; p.Name = "x"
Slices & maps
13s := []int{1, 2, 3}
s = make([]int, 0, 10)
s = append(s, 4, 5)
n := copy(dst, src)
s[1:3]
len(s), cap(s)
var s []int; s = append(s, 1)
m := map[string]int{"a": 1}
v, ok := m["key"]
delete(m, "key")
for k, v := range m { ... }
slices.Contains(s, 3)
slices.Sort(s); maps.Keys(m)
Control flow
10for i := 0; i < n; i++ { ... }
for i, v := range items { ... }
for cond { ... }
for { ... }
for i := range 10 { ... }
if err := load(); err != nil { ... }
switch status { case "on": ... default: ... }
switch { case n > 10: ... }
switch v := x.(type) { case int: ... }
outer: for { break outer }
Functions & defer
9func add(a, b int) int { return a + b }
func load() ([]byte, error)
func div(a, b int) (q int, err error)
func sum(ns ...int) int
defer f.Close()
defer mu.Unlock() // LIFO order
counter := func() int { n++; return n }
type Handler func(w, r)
apply(items, strings.ToUpper)
Interfaces & type assertions
10type Stringer interface { String() string }
// no "implements" keyword
io.Reader / io.Writer
var x any = 42
s, ok := x.(string)
switch v := x.(type) { case string: ... }
type ReadCloser interface { Reader; Closer }
func Save(w io.Writer, u User) error
func NewStore() *Store
var _ Stringer = (*User)(nil)
Error handling
10if err != nil { return err }
errors.New("not found")
fmt.Errorf("load %s: %w", path, err)
errors.Is(err, os.ErrNotExist)
var pe *fs.PathError; errors.As(err, &pe)
var ErrNotFound = errors.New("not found")
func (e *ValidationError) Error() string
errors.Join(err1, err2)
defer func() { recover() }()
panic("unreachable")
Goroutines & channels
12go work()
ch := make(chan int)
ch := make(chan int, 10)
ch <- v / v := <-ch
close(ch); for v := range ch { ... }
select { case v := <-a: ... case b <- x: ... }
var wg sync.WaitGroup; wg.Add(1); wg.Wait()
defer wg.Done()
for job := range jobs { results <- run(job) }
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
select { case <-ctx.Done(): return ctx.Err() }
var mu sync.Mutex; mu.Lock(); defer mu.Unlock()
Generics
9func Map[T, U any](s []T, f func(T) U) []U
func Keys[K comparable, V any](m map[K]V) []K
type Number interface { ~int | ~float64 }
func Sum[T Number](ns []T) T
type Stack[T any] struct { items []T }
s := Stack[int]{}
doubled := Map(nums, double)
func Min[T cmp.Ordered](a, b T) T
min(a, b), max(a, b)
Standard library gems
14strings.Split(s, ","); strings.Join(parts, "-")
strings.Contains, HasPrefix, TrimSpace
n, err := strconv.Atoi("42")
time.Now(); time.Since(start)
t.Format("2006-01-02 15:04")
time.Sleep(200 * time.Millisecond)
data, err := os.ReadFile("cfg.json")
os.WriteFile(path, data, 0o644)
os.Getenv("HOME"); filepath.Join(dir, f)
json.Marshal(v); json.Unmarshal(b, &v)
resp, err := http.Get(url); defer resp.Body.Close()
http.HandleFunc("/", h); http.ListenAndServe(":8080", nil)
slog.Info("started", "port", 8080)
sc := bufio.NewScanner(f); for sc.Scan()
Testing & benchmarks
11func TestAdd(t *testing.T) { ... }
t.Errorf("got %d, want %d", got, want)
t.Fatalf("setup failed: %v", err)
tests := []struct{ in, want int }{...}
t.Run(tc.name, func(t *testing.T) {...})
t.Helper()
t.Parallel()
func BenchmarkAdd(b *testing.B) { for range b.N { add(1, 2) } }
go test -bench=. -benchmem
go test -run TestAdd ./...
go test -cover ./...
Go CLI
11go mod init example.com/app
go mod tidy
go get github.com/pkg/x@latest
go run .
go build ./...
go test ./...
go vet ./...
gofmt -w .
go install golang.org/x/tools/...@latest
GOOS=linux GOARCH=amd64 go build
go doc strings.Split
No entry matches “:q”.
About Go Cheat Sheet
This Go cheat sheet condenses idiomatic Go into one searchable page: basics, types, structs and methods, slices and maps, control flow, functions and defer, interfaces and type assertions, error handling, goroutines and channels, generics, standard library gems, testing and benchmarks, and the go command line.
It focuses on the things Go developers look up rather than memorize — the exact slice trick to delete an element, how errors.Is and errors.As differ, the select statement with a timeout, a table-driven test, or which go command runs what — with a short explanation on every row.
The sheet is free and client-side: filter rows live with the search box, hop between sections with the sticky table of contents, copy any snippet with one click and print the page for reference while you code.
How to use Go Cheat Sheet
- Skim the sections, from Basics and Slices & maps through Goroutines & channels to the Go CLI.
- Search for a keyword such as channel, defer or errors.Is to filter every row live.
- Jump to Interfaces or Generics when you need the type syntax rather than a command.
- Click a snippet or its copy icon to copy the Go code to your clipboard.
- Print the sheet for an offline Go reference.