All cheatsheets

Cheatsheets

Go

Packages, structs & interfaces, goroutines & channels, error handling, and modules.

Test yourself

61 entries

Packages, vars & constants10

package main

Every file starts with a package clause; `main` builds an executable.

func main() {}

Entry point — only in package `main`, takes no args, returns nothing.

import ( "fmt" "os" )

Grouped import block — the idiomatic form for multiple packages.

Exported vs unexported (Capital = public)

Identifier visibility is set by the FIRST letter's case, not a keyword.

var x int = 10 / var x = 10

Declare with explicit type, or let the value infer it.

x := 10

Short variable declaration — declare + infer + assign, inside functions only.

a, b := 1, 2 / _ = value

Multiple assignment; blank identifier `_` discards a value.

const Pi = 3.14159

Compile-time constant; cannot be reassigned.

const ( A = iota; B; C )

iota — an auto-incrementing constant generator for enums and bit flags.

func init() {}

Runs at package load, before main; multiple per file/package allowed, in declaration order.

Types & structs8

int int64 uint byte rune

byte = uint8, rune = int32 (a Unicode code point).

float64 complex128 bool

Numeric and boolean primitives; the default float is float64.

type Celsius float64

Named type — a distinct type sharing an underlying one.

type User struct { Name string; Age int }

Struct — a typed collection of fields; Go's main data aggregate.

Name string `json:"name"`

Struct tags — metadata strings read by reflection (encoding/json, etc.).

type Point struct { X, Y int }

Multiple same-typed fields declared on one line.

struct { io.Reader; io.Closer }

Embedding — promote an embedded type's fields and methods.

type Handler func(int) error

Function type — functions are first-class values in Go.

Methods & interfaces6

func (u User) Greet() string

Method with a VALUE receiver — operates on a copy of u.

func (u *User) SetName(n string)

Pointer receiver — mutate the original and avoid copying.

type Reader interface { Read([]byte) (int, error) }

Interface — a set of method signatures, satisfied IMPLICITLY by any type with those methods.

interface{} / any

The empty interface — holds any value; `any` is its 1.18+ alias and the preferred spelling.

v, ok := x.(T)

Type assertion — extract a concrete type from an interface, safely.

var _ io.Writer = (*File)(nil)

Compile-time assertion that *File satisfies io.Writer.

Slices, maps & arrays7

var a [3]int

Array — FIXED length, part of its type; copied on assignment.

s := []int{1, 2, 3}

Slice — a growable, reference-like view over a backing array. The everyday list type.

s = append(s, x)

Grow a slice — you MUST reassign the result; append may move the backing array.

make([]int, 5, 10)

Allocate a slice: len 5, cap 10 (pre-size to avoid reallocs).

copy(dst, src)

Copy elements; returns the number copied (min of the two lengths).

m := map[string]int{"a": 1}

Map — an unordered hash table. Reading a missing key returns the value's zero.

make(map[string]int)

Create an empty, writable map (nil maps can't be written to).

Control flow & loops6

for i := 0; i < n; i++ { }

The C-style for — Go's ONLY loop keyword; covers every loop form.

for i, v := range xs { }

range — iterate slices/arrays (index,value), maps (key,value), strings (byte-index, rune), channels.

if v, err := f(); err != nil { }

if with an initializer — scope a value to just the if/else.

switch x { case 1: ... }

switch — no fallthrough by default; cases can be expressions or types.

defer f.Close()

defer schedules a call to run when the surrounding FUNCTION returns (LIFO order).

break Outer / continue Outer

Labeled break/continue to control nested loops.

Errors6

if err != nil { return err }

The core error idiom — errors are values returned alongside results, checked explicitly.

fmt.Errorf("doing x: %w", err)

Wrap an error with context using the %w verb — preserves the underlying error.

errors.Is(err, target) / errors.As(err, &target)

Inspect a wrapped error chain: Is matches a sentinel; As extracts a typed error.

errors.New("not found")

Create a simple error; assign to a package var for a sentinel.

errors.Join(err1, err2)

Combine multiple errors into one (1.20+); Is/As see all of them.

panic / recover

panic unwinds the stack; recover (in a deferred func) stops it. For TRULY exceptional cases only.

Goroutines, channels & select6

go doWork()

Start a goroutine — a function running concurrently on the Go runtime scheduler.

ch := make(chan int)

Channel — a typed, synchronized conduit between goroutines. Send `ch <- v`, receive `v := <-ch`.

v, ok := <-ch

Receive form that reports closure: ok is false once the channel is closed and drained.

chan<- T / <-chan T

Directional channels — send-only / receive-only in a signature.

select { case <-ch: ...; default: ... }

select — wait on multiple channel operations; runs one ready case (random if several).

var mu sync.Mutex

Mutex — guard shared state when channels don't fit. Lock/Unlock around the critical section.

Closures, context & generics6

func() { ... }()

Anonymous function / closure — captures variables from its enclosing scope by reference.

ctx, cancel := context.WithCancel(parent)

context.Context — carries cancellation, deadlines, and request-scoped values across API boundaries.

context.Background() / TODO()

Root contexts: Background at the top of main/requests; TODO as a placeholder.

func Map[T, U any](s []T, f func(T) U) []U

Generic function (1.18+) — type parameters in [] keep static types instead of falling back to any.

type Number interface { ~int | ~float64 }

Constraint interface — a UNION of allowed types; `~` includes types whose underlying type matches.

type Stack[T any] struct { items []T }

Generic type — a reusable container parameterized by T.

Modules & tooling6

go mod init example.com/app

Create a module — writes go.mod with the module path (its import prefix).

go mod tidy

Sync go.mod/go.sum with the imports actually used — add missing, drop unused.

go get pkg@v1.2.3 / @latest

Add or upgrade a dependency to a specific version or the latest.

go test ./...

Run all tests in the module. Test files end in _test.go; funcs are TestXxx(t *testing.T).

go run / go build / go install

run = compile+execute a temp binary; build = produce a binary; install = put it in GOBIN.

gofmt / go vet

gofmt enforces the one true formatting; go vet catches likely bugs the compiler misses.