Skip to main content

Course Go

Go Cheatsheet

A quick, printable reference with essential Go syntax: types, zero values, flow control, defer, slices, maps, structs, interfaces, idiomatic errors, goroutines, channels, testing, and generics. Print to PDF with Ctrl/Cmd + P.

PDF / Print

Save or print this cheatsheet as PDF

Print-ready layout: open in one click and save as PDF from your browser, no account or email required.

0. Core Go Invariants & Pitfalls to Avoid

Five checks that prevent runtime panics, data races, and subtle interface bugs.

  1. Writing to a nil map panics at runtime: always initialize with make(map[K]V) or a literal map[K]V{}.
  2. Always reassign the return value of append(s, x) because reallocation may happen; slice capacities can silently alias.
  3. Only the producer should call close(ch): closing twice or sending on a closed channel triggers a panic.
  4. Remember Go’s typed-nil interface trap: a typed nil pointer stored in an error interface is NOT == nil.
  5. Inspect every returned error and wrap with %w instead of discarding with _.

1. Declarations & Types

  • Variables

    var x int = 10        // explicit
    var y = 3.14          // inferred
    z := "hello"          // short, only inside functions
    const Pi = 3.14159    // constant

    := only works inside functions; package-level bindings require var or const.

    Pitfall: Using := inside an if/for block can accidentally shadow an outer variable or err instead of assigning to it.

  • Basic types

    bool                  // true / false
    int  int8  int16  int32  int64
    uint uint8 ... uintptr
    byte = uint8          // alias
    rune = int32          // Unicode code point
    float32 float64
    string                // immutable UTF-8 bytes

    byte and rune are idiomatic aliases for raw bytes and Unicode characters.

    Pitfall: len(s) counts UTF-8 bytes, not characters: use utf8.RuneCountInString(s) when counting runes.

  • Zero values

    var i int            // 0
    var s string         // ""
    var b bool           // false
    var p *int           // nil
    var m map[string]int // nil
    var sl []int         // nil (len 0, cap 0)

    Every declared variable starts with a deterministic zero value — no undefined.

    Pitfall: You can append() onto a nil slice safely, whereas assigning to a nil map panics immediately.

  • Conversions

    i := 42
    f := float64(i)       // 42.0
    s := string(rune(65)) // "A"
    // string <-> number: use strconv
    n, err := strconv.Atoi("42")
    s = strconv.Itoa(42)

    Go never performs implicit numeric or string conversions.

    Pitfall: string(42) does NOT produce "42" — it turns 42 into Unicode character U+002A ("*"); use strconv.Itoa(42).

2. Flow Control

  • if with init

    if v, err := fetch(); err != nil {
        return err
    } else {
        use(v)
    }
    // no parentheses around condition
    // opening brace { on the same line (enforced by gofmt)

    The init-declared variable stays scoped to the if and else branches.

    Pitfall: Putting { on a new line causes a compile error due to automatic semicolon insertion.

  • for (only loop)

    for i := 0; i < 10; i++ { ... } // classic
    for cond { ... }                // while
    for { ... }                     // infinite
    for i, v := range slice { ... }
    for k, v := range m { ... }     // non-deterministic order
    for v := range ch { ... }

    One keyword handles C-style loops, while conditions, infinite loops, and range.

    Pitfall: Map iteration order is randomized on purpose: sort the keys first whenever you need deterministic output.

  • switch

    switch x {
    case 1, 2:
        ...
    case 3:
        ...
    default:
        ...
    }
    // tagless switch behaves like clean if / else if
    switch {
    case a > b:
        ...
    case a < b:
        ...
    }

    Cases break automatically with no implicit fallthrough.

    Pitfall: Using fallthrough jumps unconditionally to the next case body without checking its condition.

  • defer

    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer f.Close()
    // executed LIFO when the surrounding function returns
    // arguments are evaluated immediately at defer time

    Guarantees cleanup on every return path of the enclosing function.

    Pitfall: Deferring f.Close() inside a loop holds all files open until the outer function returns — extract a helper per iteration.

3. Functions

  • Definition & multiple returns

    func add(a, b int) int { return a + b }
    
    // multiple returns + named results
    func divide(a, b float64) (q float64, err error) {
        if b == 0 {
            err = errors.New("divide by zero")
            return
        }
        q = a / b
        return
    }

    Idiomatic Go functions return (result, error) pairs.

    Pitfall: Bare (naked) returns in long functions hurt readability and invite err shadowing bugs — prefer explicit return q, nil.

  • Variadics

    func sum(nums ...int) int {
        total := 0
        for _, n := range nums {
            total += n
        }
        return total
    }
    sum(1, 2, 3)
    sum([]int{1, 2, 3}...) // spread existing slice

    A variadic parameter ...T arrives inside the function as slice []T.

    Pitfall: Spreading s... shares the underlying array with the caller: avoid mutating nums in-place unexpectedly.

  • Closures

    func makeCounter() func() int {
        n := 0
        return func() int {
            n++
            return n
        }
    }
    c := makeCounter()
    c() // 1
    c() // 2

    Anonymous functions capture enclosing variables by reference.

    Pitfall: If multiple goroutines call a stateful closure concurrently, guard mutations with a mutex or atomic.

4. Slices & Arrays

  • Slices

    s := []int{1, 2, 3}
    s = append(s, 4)         // always reassign
    len(s); cap(s)
    s2 := s[1:3]             // shared backing array, watch out!
    s3 := make([]int, 0, 16) // len 0, cap 16
    copy(dst, src)

    Pre-allocate capacity with make([]T, 0, n) when size is roughly known.

    Pitfall: Appending to sub-slice s2 := s[1:3] mutates s[3] if spare capacity exists — use full-slice expression s[1:3:3] to prevent aliasing.

  • Arrays (fixed length)

    var a [3]int            // [0 0 0]
    a = [3]int{1, 2, 3}
    b := [...]int{1, 2, 3}  // compiler infers length
    // arrays are value types: passing copies all elements

    Array size [N]int is part of the static type.

    Pitfall: Passing large [N]T arrays by value copies every element; prefer slices []T or pointers *[N]T.

5. Maps

  • Create & use

    m := map[string]int{"a": 1, "b": 2}
    m["c"] = 3
    v, ok := m["x"]   // ok=false if missing (v is 0)
    delete(m, "a")
    len(m)
    for k, v := range m { ... }

    The comma-ok idiom distinguishes missing keys from keys holding zero values.

    Pitfall: Concurrent map read+write crashes the Go runtime immediately with a fatal error — synchronize with sync.RWMutex or sync.Map.

  • Initialization required

    var m map[string]int     // nil map
    // m["a"] = 1            // PANIC: assignment to entry in nil map
    m = make(map[string]int)
    m["a"] = 1               // safe

    Reading or taking len() on a nil map returns zero safely, writing panics.

    Pitfall: Always initialize map fields inside constructor helpers before returning a struct.

6. Strings

  • Operations

    s := "Hello, world"
    len(s)                       // byte length, not rune count
    strings.ToUpper(s)
    strings.Contains(s, "world")
    strings.Split(s, ", ")
    strings.Join(parts, "-")
    strings.HasPrefix(s, "Hello")
    strings.ReplaceAll(s, "o", "0")

    Standard string operations live in the strings package.

    Pitfall: Indexing s[i] reads a single raw byte (uint8) and can split multi-byte UTF-8 sequences.

  • Builder for loops

    var b strings.Builder
    for _, w := range words {
        b.WriteString(w)
        b.WriteByte(' ')
    }
    out := b.String()
    // AVOID s += w inside loops: O(n^2) allocations

    strings.Builder grows cleanly without quadratic string copying.

    Pitfall: Copying a non-empty strings.Builder by value panics on subsequent writes.

  • Iterate runes (Unicode)

    for i, r := range "café" {
        // i = byte offset, r = rune (int32)
        fmt.Printf("%d %c\n", i, r)
    }
    // len("café") == 5 (bytes), 4 runes

    for range on a string automatically decodes UTF-8 code points into runes.

    Pitfall: The loop index i advances by byte offset rather than rune count.

7. Structs & Methods

  • Structs

    type Point struct {
        X, Y float64
    }
    p := Point{X: 3, Y: 4}
    p.X = 5
    
    // pointers auto-dereference field access
    q := &Point{X: 1, Y: 2}
    _ = q.X // no (*q).X needed

    Use named struct literals (Point{X: 3, Y: 4}) so adding fields won’t break callers.

    Pitfall: Unkeyed positional literals (Point{1, 2}) silently break or fail to compile when struct fields change.

  • Methods & receivers

    func (p Point) Distance() float64 {
        return math.Hypot(p.X, p.Y)
    }
    
    // pointer receiver: mutates caller state and avoids copies
    func (p *Point) Translate(dx, dy float64) {
        p.X += dx
        p.Y += dy
    }

    Keep receiver kind consistent across a type’s method set.

    Pitfall: A value receiver modifies only a temporary copy of the struct, never the caller’s instance.

  • Composition (embedding)

    type Animal struct{ Name string }
    func (a Animal) Greet() string { return "Hi " + a.Name }
    
    type Dog struct {
        Animal        // embedded
        Breed string
    }
    d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Lab"}
    d.Greet()         // promoted from Animal

    Promotes fields and methods without classical inheritance hierarchies.

    Pitfall: Embedding is composition, not subtyping: []Dog cannot be passed where []Animal is required.

8. Interfaces & Errors

  • Interfaces

    type Stringer interface {
        String() string
    }
    // satisfied implicitly: no "implements" keyword
    func (p Point) String() string {
        return fmt.Sprintf("(%.1f, %.1f)", p.X, p.Y)
    }

    Implicit satisfaction keeps coupling minimal — prefer 1–2 method interfaces.

    Pitfall: A nil pointer of type *MyError stored in an error variable is non-nil when checked with err != nil: always return literal nil.

  • Type assertion / switch

    if s, ok := v.(string); ok {
        use(s)
    }
    
    switch x := v.(type) {
    case int:
        use(x)
    case string:
        use(x)
    default:
        fmt.Println("?")
    }

    Use comma-ok assertions or type switches to unwrap concrete interface values safely.

    Pitfall: Single-value v.(string) panics at runtime if the interface holds another type or is nil.

  • Idiomatic errors

    if err != nil {
        return fmt.Errorf("open %s: %w", path, err)
    }
    // sentinel checks
    if errors.Is(err, io.EOF) { ... }
    // typed unwrap
    var pe *fs.PathError
    if errors.As(err, &pe) { use(pe.Path) }

    Wrap underlying errors with %w so callers can inspect chains via errors.Is and errors.As.

    Pitfall: Formatting an error with %v drops the wrapped cause and silently breaks errors.Is / errors.As checks.

9. Goroutines & Channels

  • Goroutines

    go runTask(arg) // fire-and-forget
    // synchronize with WaitGroup
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        work()
    }()
    wg.Wait()

    Always call wg.Add before spawning the goroutine, never inside it.

    Pitfall: Launching goroutines without shutdown coordination or WaitGroup tracking creates goroutine leaks.

  • Channels

    ch := make(chan int)      // unbuffered (synchronizes)
    ch := make(chan int, 4)   // buffered
    ch <- 42                  // send
    v := <-ch                 // receive
    v, ok := <-ch             // ok=false if closed
    close(ch)                 // producer only
    for v := range ch { ... } // reads until closed

    Only the sender side should close a channel when no more values will be sent.

    Pitfall: Closing twice or sending to a closed channel panics; sending/receiving on a nil channel blocks forever.

  • select

    select {
    case v := <-ch1:
        use(v)
    case ch2 <- 42:
        // sent
    case <-time.After(time.Second):
        return errors.New("timeout")
    case <-ctx.Done():
        return ctx.Err()
    }

    Wait on multiple channel send/receive operations simultaneously.

    Pitfall: Calling time.After inside a loop leaks timer objects until expiry — reuse a time.NewTimer instead.

  • context

    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()
    go work(ctx)
    // inside work:
    select {
    case <-ctx.Done():
        return ctx.Err()
    case res := <-out:
        return res
    }

    Propagates timeouts and cancellation signals across goroutines and I/O calls.

    Pitfall: Always defer cancel() even when operations finish early so the background timer can be garbage-collected.

10. Essential Stdlib

  • fmt

    fmt.Println("hello", 42)
    fmt.Printf("%s = %d\n", k, v)
    // verbs: %v default, %+v fields, %#v Go-syntax, %T type, %q quoted, %w wrap
    fmt.Errorf("open %s: %w", path, err)

    Fast value inspection (%+v, %#v) and type checking (%T).

    Pitfall: Passing an integer to %s prints an error tag — use %d for integers or %v for any value.

  • io / os

    data, err := os.ReadFile(path)
    err = os.WriteFile(path, data, 0644)
    f, err := os.Open(path); defer f.Close()
    io.Copy(dst, src)
    os.Args; os.Stdin; os.Stdout; os.Stderr

    Use ReadFile/WriteFile for small payloads and io.Copy for bounded-memory streaming.

    Pitfall: Check err != nil before calling defer f.Close(), otherwise f can be nil on failure.

  • time

    t := time.Now()
    t.Format("2006-01-02 15:04:05") // reference time magic!
    d := 5 * time.Second
    t.Add(d); time.Since(t)
    time.Sleep(d)
    // Sleep(5) would sleep 5 nanoseconds!
    ticker := time.NewTicker(d); defer ticker.Stop()

    Go date layouts always format the reference timestamp Mon Jan 2 15:04:05 MST 2006.

    Pitfall: Passing YYYY-MM-DD to Format outputs literal characters instead of dates — use "2006-01-02".

  • encoding/json

    type User struct {
        Name  string `json:"name"`
        Email string `json:"email,omitempty"`
        pwd   string // unexported: ignored
    }
    b, err := json.Marshal(u)
    err = json.Unmarshal(b, &u) // POINTER
    json.NewEncoder(w).Encode(u)
    json.NewDecoder(r).Decode(&u)

    Only exported struct fields (capitalized) are marshaled and unmarshaled.

    Pitfall: Forgetting &u when calling json.Unmarshal fails because a non-pointer value cannot be populated.

11. Testing & Modules

  • Unit Tests

    // file: math_test.go
    func TestAdd(t *testing.T) {
        got := Add(2, 3)
        if got != 5 {
            t.Fatalf("got %d, want 5", got)
        }
    }

    Files ending in _test.go are compiled exclusively during go test.

    Pitfall: Test functions must start with Test followed by a capital letter (TestAdd, never testAdd).

  • Table-driven tests

    func TestDouble(t *testing.T) {
        cases := []struct {
            name     string
            in, want int
        }{
            {"zero", 0, 0},
            {"positive", 3, 6},
        }
        for _, tc := range cases {
            t.Run(tc.name, func(t *testing.T) {
                if got := Double(tc.in); got != tc.want {
                    t.Errorf("got %d, want %d", got, tc.want)
                }
            })
        }
    }

    Each test case runs as a named subtest runnable via go test -run.

    Pitfall: Call t.Helper() inside shared assertion helpers so failures report the caller line number.

  • Benchmarks & Modules

    func BenchmarkX(b *testing.B) {
        for i := 0; i < b.N; i++ { X() }
    }
    // go test -bench=. -benchmem
    // go mod init github.com/me/pkg && go mod tidy

    Built-in microbenchmarking and reproducible module dependency locking.

    Pitfall: Run go mod tidy after adding or removing imports so go.mod and go.sum stay clean.

12. Generics & Idioms

  • Generics

    func Map[T, U any](s []T, f func(T) U) []U {
        out := make([]U, len(s))
        for i, v := range s { out[i] = f(v) }
        return out
    }
    type Number interface { ~int | ~float64 }
    func Sum[T Number](nums []T) T { ... }

    The ~T approximation element allows defined types whose underlying type is T.

    Pitfall: Use comparable only for == and map keys, and cmp.Ordered for < / >; keep interfaces simple when generics aren’t needed.

  • Visibility & panic/recover

    type User struct{}       // Exported (capitalized)
    type cache struct{}      // Unexported (package-private)
    // Acronyms stay all-caps: HTTPClient, URL, ID
    
    defer func() {
        if r := recover(); r != nil {
            log.Printf("panic: %v", r)
        }
    }()

    Identifier capitalization controls package export visibility; acronyms keep uniform case.

    Pitfall: Never use panic/recover for ordinary error control flow — return explicit error values.