Search and navigate

Open full search and filters →

Golang cheatsheet

Essential Go syntax and production-minded patterns in one scannable reference. Follow the links beneath each example when you need the complete explanation.

Variables and constants

name := "gopher"
var count int
const timeout = 5 * time.Second

Functions and errors

func load(id string) (Item, error) {
  if id == "" { return Item{}, errors.New("id required") }
  return Item{ID: id}, nil
}

Slices and maps

items := []string{"a", "b"}
items = append(items, "c")
counts := map[string]int{"go": 1}

Goroutines and channels

results := make(chan Result)
go func() { results <- work() }()
result := <-results

Context timeout

ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()
result, err := fetch(ctx)

Table-driven test

for _, tc := range tests {
  t.Run(tc.name, func(t *testing.T) {
    if got := fn(tc.in); got != tc.want { t.Errorf("got %v", got) }
  })
}

Need more context? Follow the structured Go roadmap →