contentintech
Learn/languages/Go/Cheatsheet
Intermediate

Go Cheatsheet

A quick-reference cheatsheet for Go syntax covering declarations, functions, structs, interfaces, concurrency, error handling, and common tooling.

GoroutinesChannelsInterfacesError Handling
NotesCheatsheet

Declarations

Variables & Constants

var x int = 10        // explicit
var y = 3.14           // inferred
z := "short"           // := (func scope)
var a, b = 1, 2        // multiple

const Pi = 3.14159
const (
    A = iota           // 0
    B                  // 1
    C                  // 2
)

Types

int int8 int16 int32 int64
uint uint8(byte) uint32 uint64
float32 float64 complex128
bool string rune (int32)

type Celsius float64  // named type
type ID = int64       // alias

Functions & Defer

func add(a, b int) int { return a + b }

// multiple returns
func divmod(a, b int) (int, int) {
    return a / b, a % b
}

// variadic
func sum(ns ...int) int { /* ... */ }
sum(nums...)          // spread

// closure
inc := func() int { i++; return i }

defer f.Close()       // runs on return (LIFO)

Structs & Methods

type Point struct {
    X, Y int
}
p := Point{X: 1, Y: 2}
p2 := &Point{1, 2}    // pointer

// value receiver: gets a copy
func (p Point) Sum() int { return p.X + p.Y }

// pointer receiver: can mutate
func (p *Point) Shift(d int) { p.X += d }

Interfaces

type Reader interface {
    Read(p []byte) (int, error)
}
// implicit: any type with Read satisfies it

var v any = 42        // any == interface{}

// type assertion (comma-ok)
if n, ok := v.(int); ok { /* ... */ }

// type switch
switch x := v.(type) {
case int:    _ = x
case string: _ = x
default:     _ = x
}

Slices & Maps

Slices

s := []int{1, 2, 3}
s = make([]int, 0, 8) // len 0, cap 8
s = append(s, 4)
sub := s[1:3]         // shares backing array
copy(dst, src)        // independent copy
len(s); cap(s)

Maps

m := map[string]int{"a": 1}
m["b"] = 2
v, ok := m["a"]       // ok false if missing
delete(m, "a")
for k, v := range m { /* random order */ }

Generics

func Max[T cmp.Ordered](a, b T) T {
    if a > b { return a }
    return b
}

type Number interface { ~int | ~float64 }

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

Error Handling

if err != nil {
    return fmt.Errorf("ctx: %w", err) // wrap
}

var ErrNotFound = errors.New("not found")
errors.Is(err, ErrNotFound)   // sentinel

var pe *fs.PathError
errors.As(err, &pe)           // typed extract

// panic / recover
defer func() {
    if r := recover(); r != nil { /* ... */ }
}()

Goroutines, Channels & Select

go doWork()               // launch goroutine

ch := make(chan int)      // unbuffered
buf := make(chan int, 4)  // buffered

ch <- 42                  // send
v := <-ch                 // receive
v, ok := <-ch             // ok false if closed
close(ch)
for v := range ch { }     // until closed

chan<- int                // send-only
<-chan int                // receive-only

select {
case v := <-ch:
    _ = v
case ch2 <- 1:
case <-time.After(time.Second):
default:                  // non-blocking
}

Sync & Context

var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); /* ... */ }()
wg.Wait()

var mu sync.Mutex
mu.Lock(); mu.Unlock()

var once sync.Once
once.Do(func() { /* init */ })

ctx, cancel := context.WithTimeout(
    context.Background(), 2*time.Second)
defer cancel()
<-ctx.Done()              // ctx.Err()

Stdlib Snippets

// HTTP server
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)

// JSON
data, _ := json.Marshal(v)
json.Unmarshal(data, &v)
// tags: `json:"name,omitempty"`

// files
b, _ := os.ReadFile("f.txt")
os.WriteFile("f.txt", b, 0644)

// strings / strconv
strings.Split(s, ",")
n, _ := strconv.Atoi("42")

Go Commands

go mod init example.com/app
go get pkg@latest
go mod tidy
go build ./...
go run .
go test ./... -race -cover
go vet ./...
gofmt -w .        # or: go fmt ./...
go install ./...

# Go 1.22+
for i := range 5 { }   // range over int
# loop var is per-iteration (no capture bug)

Section navigation