Go Cheat Sheet: Golang Syntax, Slices, Maps, Interfaces, Errors, Goroutines, Channels and Modules
go-cheatsheet is a fast, practical Go (Golang) reference for developers who know another language and want to write idiomatic Go. It covers syntax and types, slices and maps (with the slices and maps packages), structs, methods and interfaces, error handling with errors.Is / errors.As, generics, iterators, goroutines, channels, select, sync and context, concurrency patterns like worker pools and pipelines, testing and benchmarks, and Go modules.
The bigger examples live in examples/ as a real Go package with table-driven tests.
Last reviewed: December 2026. Current Go release line: Go 1.27 (released August 2026). Features newer than Go 1.21 are marked with the version that added them. Check go.dev/doc/devel/release for the latest.
git clone https://github.com/Ralpberry-Labs/go-cheatsheet
cd go-cheatsheet
go test ./... # needs Go 1.25+
go test -bench . ./examples
Table of Contents
- Hello World and Tooling
- Variables, Constants and Types
- Control Flow
- Functions
- Pointers
- Arrays and Slices
- Maps
- Strings, Runes and Bytes
- Structs and Methods
- Interfaces
- Errors
- Generics
- Iterators (range over func)
- Goroutines and Channels
- select
- sync and atomic
- context
- Concurrency Patterns
- Standard Library Quick Reference
- Testing
- Modules and Packages
- go Command Cheat Sheet
- Common Gotchas
- Go Version Feature Table
- Resources
- Which Concurrency Tool When
- Go vs Other Languages
- FAQ
- Where to Go Next
- Contributing
- License
- More free resources
Hello World and Tooling
package main
import "fmt"
func main() {
fmt.Println("Hello, Go")
}
go mod init example.com/hello # create go.mod
go run . # compile and run
go build -o hello . # build a binary
go fmt ./... # format (gofmt); everybody uses it
go vet ./... # catch suspicious code
Rules worth knowing on day one:
- Every file starts with
package name.package mainwithfunc main()builds an executable. - Exported names start with a capital letter (
fmt.Println); lowercase names are package-private. - Unused imports and unused local variables are compile errors.
- Formatting is not a debate: run
gofmt(your editor does it on save with gopls).
Variables, Constants and Types
var a int // zero value: 0
var b, c = 1, "two" // type inferred
d := 3.14 // short declaration, only inside functions
var (
name string = "go"
ready bool
)
const Pi = 3.14159 // untyped constant: adapts to context
const MaxSize int64 = 1 << 20
// iota: auto-incrementing constant generator
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
)
const (
_ = iota
KB = 1 << (10 * iota) // 1024
MB // 1048576
GB
)
Basic types and zero values
| Type | Zero value | Notes |
|---|---|---|
bool |
false |
|
int, int8 … int64 |
0 |
int is 64-bit on 64-bit platforms |
uint, uint8 … uint64, uintptr |
0 |
byte = uint8 |
float32, float64 |
0 |
Use float64 by default |
complex64, complex128 |
0 |
|
string |
"" |
Immutable bytes, usually UTF-8 |
rune |
0 |
Alias for int32, one Unicode code point |
| pointers, slices, maps, channels, functions, interfaces | nil |
|
| structs | each field’s zero value |
Conversions
Go has no implicit numeric conversion:
i := 42
f := float64(i)
u := uint(f)
s := strconv.Itoa(i) // int -> "42"
n, err := strconv.Atoi("42") // "42" -> int
x, err := strconv.ParseFloat("3.5", 64)
str := fmt.Sprint(3.5) // any -> string
b := []byte("hi") // string <-> []byte copies
r := []rune("héllo") // string -> code points
string(65) gives "A" (a rune), not "65". go vet warns about it; use strconv.Itoa.
Type definitions vs aliases
type Celsius float64 // new named type: needs explicit conversion
type MyInt = int // alias: identical to int
Control Flow
// if with a short statement: err is scoped to the if/else
if v, err := strconv.Atoi(s); err != nil {
return err
} else if v > 10 {
fmt.Println("big")
}
// for is the only loop
for i := 0; i < 10; i++ {}
for cond {} // while
for {} // forever
for i := range 10 {} // 0..9 (Go 1.22+)
for i, v := range []string{"a", "b"} {}
for k, v := range m {} // map order is random
for i, r := range "héllo" {} // i = byte offset, r = rune
for v := range ch {} // until the channel is closed
// labels for nested loops
outer:
for _, row := range grid {
for _, cell := range row {
if cell == target {
break outer
}
}
}
// switch: no fallthrough by default, cases can be lists or expressions
switch day {
case "sat", "sun":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
switch { // like if/else chains
case score >= 90:
grade = "A"
case score >= 80:
grade = "B"
}
// defer: runs when the function returns, LIFO order
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
Deferred call arguments are evaluated immediately; the call itself runs at return. A deferred closure can modify named return values (used with recover).
Functions
func add(a, b int) int { return a + b }
// Multiple return values (value, error) is the standard pattern
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named results
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // "naked" return: fine in tiny functions only
}
// Variadic
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
sum(1, 2, 3)
sum(slice...) // spread a slice
// Functions are values; closures capture variables
func counter() func() int {
n := 0
return func() int { n++; return n }
}
next := counter()
next() // 1
next() // 2
// Function types
type Middleware func(http.Handler) http.Handler
Go has no default parameters, overloading or exceptions. Use option structs, the functional options pattern or separate functions.
Functional options pattern:
type Server struct{ port int; timeout time.Duration }
type Option func(*Server)
func WithPort(p int) Option { return func(s *Server) { s.port = p } }
func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func NewServer(opts ...Option) *Server {
s := &Server{port: 8080, timeout: 30 * time.Second}
for _, o := range opts {
o(s)
}
return s
}
srv := NewServer(WithPort(9000))
Pointers
x := 10
p := &x // p is *int
*p = 20 // x is now 20
fmt.Println(x) // 20
func reset(n *int) { *n = 0 }
reset(&x)
pp := new(int) // pointer to a zero int
q := new(42) // Go 1.26+: new accepts an expression, q points to 42
There is no pointer arithmetic. Taking the address of a local is safe: the compiler moves it to the heap if it escapes. Use pointers to share or mutate, or to avoid copying large structs; use values for small, immutable data.
Arrays and Slices
Arrays have a fixed size that is part of the type ([3]int). You almost always use slices: a view (pointer, length, capacity) onto an array.
var a [3]int // array: [0 0 0]
s := []int{1, 2, 3} // slice literal
s2 := make([]int, 0, 10) // len 0, cap 10
s = append(s, 4, 5) // may reallocate: always use the result
s = append(s, other...) // append a slice
len(s); cap(s)
sub := s[1:3] // elements 1 and 2, shares memory with s
full := s[1:3:3] // 3-index slice: cap limited, next append copies
c := make([]int, len(s))
n := copy(c, s) // returns number copied
// 2D slice
grid := make([][]int, rows)
for i := range grid {
grid[i] = make([]int, cols)
}
// Remove element i (order kept)
s = append(s[:i], s[i+1:]...)
// or, clearer:
s = slices.Delete(s, i, i+1)
The slices package (Go 1.21+)
import "slices"
slices.Sort(nums)
slices.SortFunc(people, func(a, b Person) int { return cmp.Compare(a.Age, b.Age) })
slices.SortStableFunc(people, cmpFn)
slices.Contains(nums, 3)
slices.Index(nums, 3) // -1 if missing
slices.IndexFunc(people, func(p Person) bool { return p.Name == "Ada" })
slices.BinarySearch(sorted, 7) // (index, found)
slices.Max(nums); slices.Min(nums) // panic on empty slice
slices.Reverse(nums)
slices.Equal(a, b)
slices.Clone(nums)
slices.Compact(sorted) // remove consecutive duplicates
slices.Insert(nums, 1, 10, 11)
slices.Delete(nums, 1, 3)
slices.Concat(a, b, c) // Go 1.22
slices.Repeat([]int{0}, 5) // Go 1.23
slices.Collect(seq) // iterator -> slice (Go 1.23)
slices.Sorted(maps.Keys(m)) // sorted map keys (Go 1.23)
slices.Chunk(nums, 3) // iterator of sub-slices (Go 1.23)
Sort by several fields with cmp.Or (Go 1.22):
slices.SortFunc(people, func(a, b Person) int {
return cmp.Or(
cmp.Compare(a.Age, b.Age),
strings.Compare(a.Name, b.Name),
)
})
Slice gotchas
a := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 99) // overwrites a[2]! b still had capacity in a's array
fmt.Println(a) // [1 2 99 4]
Use slices.Clone or a 3-index slice when you hand out sub-slices you do not want modified. A nil slice and an empty slice both have len 0 and work with append and range; they differ in JSON (null vs []).
Maps
m := map[string]int{"a": 1, "b": 2}
m2 := make(map[string][]string) // make before writing: writing to a nil map panics
m["c"] = 3
v := m["missing"] // zero value (0), no error
v, ok := m["a"] // comma-ok idiom
if _, ok := m["x"]; !ok { /* not present */ }
delete(m, "a")
clear(m) // remove everything (Go 1.21)
len(m)
for k, v := range m {} // random order every time
// Set
seen := map[string]struct{}{}
seen["x"] = struct{}{}
// Count
counts := map[string]int{}
for _, w := range words {
counts[w]++
}
// Group
groups := map[string][]Person{}
groups[p.City] = append(groups[p.City], p) // nil slice append is fine
The maps package
import "maps"
keys := slices.Sorted(maps.Keys(m)) // deterministic order
vals := slices.Collect(maps.Values(m))
copyOfM := maps.Clone(m)
maps.Copy(dst, src)
maps.Equal(m1, m2)
maps.DeleteFunc(m, func(k string, v int) bool { return v == 0 })
Maps are not safe for concurrent writes. Protect with a sync.Mutex, or use sync.Map for the specific case of keys written once and read many times.
Map keys must be comparable: no slices, maps or functions as keys. Structs and arrays of comparable types work.
Strings, Runes and Bytes
s := "héllo"
len(s) // 6 (bytes!)
utf8.RuneCountInString(s) // 5 (characters)
s[1] // a byte (195), not a character
for i, r := range s {} // iterates runes with byte offsets
strings.Contains(s, "ll")
strings.HasPrefix(s, "h"); strings.HasSuffix(s, "o")
strings.Index(s, "l")
strings.Split("a,b,c", ",") // ["a" "b" "c"]
strings.Fields(" a b ") // ["a" "b"] (splits on whitespace)
strings.Join([]string{"a", "b"}, "-")
strings.ReplaceAll(s, "l", "L")
strings.ToUpper(s); strings.ToLower(s)
strings.TrimSpace(" x ")
strings.Trim("--x--", "-")
strings.TrimPrefix(s, "h")
strings.Cut("key=value", "=") // ("key", "value", true)
strings.EqualFold("Go", "GO") // case-insensitive equality
strings.Repeat("ab", 3)
// Efficient building
var b strings.Builder
for i := range 3 {
fmt.Fprintf(&b, "%d,", i)
}
result := b.String() // "0,1,2,"
fmt verbs
| Verb | Prints | Example output |
|---|---|---|
%v |
default format | {Ada 36} |
%+v |
struct with field names | {Name:Ada Age:36} |
%#v |
Go syntax | main.Person{Name:"Ada", Age:36} |
%T |
type | main.Person |
%d |
integer | 42 |
%5d / %-5d / %05d |
width, left-align, zero pad | ` 42 / 42 ` / 00042 |
%x / %X |
hex | 2a |
%b / %o |
binary / octal | 101010 |
%f / %.2f / %e / %g |
floats | 3.141593 / 3.14 |
%s / %q |
string / quoted string | hi / "hi" |
%c / %U |
character / Unicode | A / U+0041 |
%t |
bool | true |
%p |
pointer | 0xc000012345 |
%w |
wrap error (only in fmt.Errorf) |
fmt.Println adds spaces and a newline; fmt.Printf formats; fmt.Sprintf returns a string; fmt.Fprintf(w, ...) writes to any io.Writer.
Structs and Methods
type Person struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Email string `json:"-"` // never in JSON
private int // unexported: invisible to other packages and to encoding/json
}
p := Person{Name: "Ada", Age: 36} // keyed literal (preferred)
pp := &Person{Name: "Linus"} // pointer to a new struct
pp.Age = 54 // auto-dereference: no -> operator
// Anonymous struct, handy in tests and JSON
point := struct{ X, Y int }{1, 2}
// Methods: value receiver (copy) vs pointer receiver (can modify)
func (p Person) Greeting() string { return "Hi, " + p.Name }
func (p *Person) Birthday() { p.Age++ }
p.Birthday() // Go takes &p automatically for addressable values
Choosing a receiver: use a pointer receiver if the method mutates, if the struct is large, or if any other method on the type uses a pointer receiver (be consistent). Use value receivers for small immutable types like time.Time.
Embedding (composition, not inheritance)
type Animal struct{ Name string }
func (a Animal) Describe() string { return "I am " + a.Name }
type Dog struct {
Animal // embedded: fields and methods are promoted
Breed string
}
d := Dog{Animal: Animal{Name: "Rex"}, Breed: "lab"}
d.Name // promoted field
d.Describe() // promoted method
Constructors are plain functions named NewX that return X or *X. Make the zero value useful when you can (var mu sync.Mutex and var b bytes.Buffer work without initialization).
Interfaces
Interfaces are satisfied implicitly: any type with the right methods implements the interface. No implements keyword.
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }
var s Shape = Rect{3, 4}
// Compile-time check that a type implements an interface
var _ Shape = Rect{}
var _ io.Writer = (*bytes.Buffer)(nil)
Common standard interfaces:
| Interface | Method(s) | Used by |
|---|---|---|
fmt.Stringer |
String() string |
fmt.Print* |
error |
Error() string |
everything |
io.Reader |
Read(p []byte) (n int, err error) |
files, HTTP bodies, network |
io.Writer |
Write(p []byte) (n int, err error) |
files, buffers, HTTP responses |
io.Closer |
Close() error |
resources |
sort.Interface |
Len, Less, Swap |
sort.Sort (prefer slices.SortFunc) |
http.Handler |
ServeHTTP(w, r) |
net/http |
json.Marshaler |
MarshalJSON() ([]byte, error) |
encoding/json |
Type assertions and type switches
var x any = "hello" // any = interface{}
s := x.(string) // panics if x is not a string
s, ok := x.(string) // safe form
switch v := x.(type) {
case string:
fmt.Println("string of length", len(v))
case int, int64:
fmt.Println("integer", v)
case nil:
fmt.Println("nil")
default:
fmt.Printf("other %T\n", v)
}
Idioms: accept interfaces, return concrete types. Keep interfaces small (one or two methods) and define them where they are used, not where they are implemented.
Errors
Errors are values. Functions return error as the last result; callers check it right away.
f, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("open config: %w", err) // wrap with context
}
defer f.Close()
Full tested examples: examples/errors.go.
// Sentinel errors: fixed values compared with errors.Is
var ErrNotFound = errors.New("not found")
// Custom error types: extra fields, matched with errors.As
type ValidationError struct{ Field, Msg string }
func (e *ValidationError) Error() string { return e.Field + ": " + e.Msg }
// Checking
if errors.Is(err, ErrNotFound) { /* 404 */ }
if errors.Is(err, os.ErrNotExist) { /* file missing */ }
if errors.Is(err, context.DeadlineExceeded) { /* timeout */ }
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("bad field:", ve.Field)
}
// Combine several errors (Go 1.20)
err := errors.Join(err1, err2) // errors.Is matches either
| Do | Don’t |
|---|---|
fmt.Errorf("load user %d: %w", id, err) |
return err with no context from deep layers |
errors.Is(err, ErrX) |
err == ErrX (fails on wrapped errors) |
Lowercase messages without punctuation: "open config: file not found" |
"Failed to open config!" |
| Handle an error once (log it or return it) | Log and return, producing duplicate logs |
Use %w only when callers may inspect the cause |
Leak implementation details through %w in public APIs |
panic and recover
panic is for programmer bugs and impossible states, not normal errors. recover only works inside a deferred function:
func safe(f func()) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
f()
return nil
}
net/http recovers panics per request; your own goroutines do not, and an unrecovered panic in any goroutine crashes the program.
Generics
Type parameters (Go 1.18+). Full examples: examples/collections.go.
func Map[T, U any](in []T, f func(T) U) []U {
out := make([]U, 0, len(in))
for _, v := range in {
out = append(out, f(v))
}
return out
}
lengths := Map([]string{"a", "bb"}, func(s string) int { return len(s) }) // T, U inferred
// Constraints
func Max[T cmp.Ordered](a, b T) T { if a > b { return a }; return b } // or the builtin max (Go 1.21)
func Keys[K comparable, V any](m map[K]V) []K { /* ... */ }
// Custom constraint with a type set; ~ includes named types with that underlying type
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
type Celsius float64
Sum([]Celsius{1.5, 2}) // works thanks to ~float64
// Generic types
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
v := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v, true
}
type Pair[K comparable, V any] struct {
Key K
Val V
}
| Constraint | Allows |
|---|---|
any |
Every type |
comparable |
Types usable with == and as map keys |
cmp.Ordered |
Integers, floats, strings (<, > work) |
~int \| ~string |
Those types and named types based on them |
interface{ String() string } |
Types with that method |
Generic methods: since Go 1.27, a method can declare its own type parameters (for example func (r *Rand) N[T intType](n T) T in math/rand/v2). Before 1.27, only functions and types could. Interface methods still cannot have type parameters.
When to use generics: containers, algorithms over slices/maps/channels, and functions that would otherwise take any and type-assert. Do not use them when an interface with a method describes the behaviour better.
Iterators (range over func)
Since Go 1.23, range works over functions, and the iter package defines the standard shapes:
// iter.Seq[V] = func(yield func(V) bool)
// iter.Seq2[K,V] = func(yield func(K, V) bool)
func Fibonacci() iter.Seq[int] {
return func(yield func(int) bool) {
a, b := 0, 1
for {
if !yield(a) { // false means the loop body did break/return
return
}
a, b = b, a+b
}
}
}
for n := range Fibonacci() {
if n > 100 {
break
}
fmt.Println(n)
}
Standard library functions that return or accept iterators: maps.Keys, maps.Values, maps.All, slices.All, slices.Values, slices.Backward, slices.Collect, slices.Sorted, slices.Chunk, strings.Lines, strings.SplitSeq, strings.FieldsSeq (the last three are Go 1.24). Examples: examples/iterators.go.
Goroutines and Channels
A goroutine is a function running concurrently, managed by the Go runtime (cheap: a few KB of stack that grows as needed).
go doWork() // fire and forget: something must wait for it
go func(msg string) { fmt.Println(msg) }("hi")
Channels connect goroutines:
ch := make(chan int) // unbuffered: send blocks until a receiver is ready
buf := make(chan int, 10) // buffered: send blocks only when full
ch <- 42 // send
v := <-ch // receive
v, ok := <-ch // ok == false: channel closed and drained
close(ch) // only the sender closes; sending on a closed channel panics
for v := range ch {} // receive until closed
// Direction in signatures documents intent and is checked by the compiler
func producer(out chan<- int) {}
func consumer(in <-chan int) {}
| Operation | nil channel | closed channel | open channel |
|---|---|---|---|
| send | blocks forever | panic | blocks until received / buffer space |
| receive | blocks forever | zero value, ok=false immediately |
blocks until a value |
| close | panic | panic | succeeds |
Waiting for goroutines:
var wg sync.WaitGroup
for _, url := range urls {
wg.Go(func() { // Go 1.25+: does Add(1), go, and Done for you
fetch(url)
})
}
wg.Wait()
// Before Go 1.25:
wg.Add(1)
go func() {
defer wg.Done()
fetch(url)
}()
Since Go 1.22, each loop iteration has its own copy of the loop variable, so capturing url in the closure is safe.
select
select waits on several channel operations and runs the first that is ready (random choice if several are).
select {
case msg := <-messages:
fmt.Println(msg)
case results <- value:
fmt.Println("sent")
case <-time.After(2 * time.Second):
fmt.Println("timeout")
case <-ctx.Done():
return ctx.Err()
}
// Non-blocking send/receive with default
select {
case ch <- v:
default:
fmt.Println("channel full, dropping")
}
// Ticker loop
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case t := <-ticker.C:
fmt.Println("tick", t)
case <-ctx.Done():
return
}
}
sync and atomic
var mu sync.Mutex
mu.Lock()
counter++
mu.Unlock()
var rw sync.RWMutex // many readers OR one writer
rw.RLock(); _ = cache[k]; rw.RUnlock()
var once sync.Once
once.Do(initConfig) // exactly once, even from many goroutines
getConfig := sync.OnceValue(loadConfig) // Go 1.21: lazily computed, cached
cfg := getConfig()
var n atomic.Int64 // typed atomics (Go 1.19)
n.Add(1)
n.Load()
var pool = sync.Pool{New: func() any { return new(bytes.Buffer) }} // reuse temporary objects
Guard data, not code: put the mutex next to the fields it protects, and never copy a struct that contains a mutex (pass a pointer). go vet reports copies.
Detect data races with go test -race ./... or go run -race ..
context
context.Context carries cancellation, deadlines and request-scoped values across API boundaries. It is the first parameter, named ctx.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // always call cancel to free resources
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := http.DefaultClient.Do(req)
if errors.Is(err, context.DeadlineExceeded) { /* timed out */ }
ctx, cancel := context.WithCancel(parent)
ctx, cancel := context.WithDeadline(parent, time.Now().Add(time.Minute))
ctx, cancel := context.WithCancelCause(parent) // cancel(err); context.Cause(ctx) (Go 1.20)
ctx = context.WithoutCancel(parent) // keep values, drop cancellation (Go 1.21)
stop := context.AfterFunc(ctx, cleanup) // run cleanup when ctx is done (Go 1.21)
// Values: for request-scoped data (request ID, auth), not optional parameters
type ctxKey struct{}
ctx = context.WithValue(ctx, ctxKey{}, "req-123")
id, _ := ctx.Value(ctxKey{}).(string)
// Respect cancellation in long loops
for _, item := range items {
if err := ctx.Err(); err != nil {
return err
}
process(item)
}
In an HTTP handler use r.Context(); it is cancelled when the client disconnects. In tests, t.Context() (Go 1.24) is cancelled when the test ends.
Concurrency Patterns
All of these are implemented and tested in examples/concurrency.go.
Worker pool
func WorkerPool(jobs []int, n int, work func(int) int) []int {
jobCh := make(chan int)
resCh := make(chan int)
var wg sync.WaitGroup
for range n {
wg.Go(func() {
for j := range jobCh {
resCh <- work(j)
}
})
}
go func() {
for _, j := range jobs {
jobCh <- j
}
close(jobCh)
}()
go func() { wg.Wait(); close(resCh) }()
var results []int
for r := range resCh {
results = append(results, r)
}
return results
}
Bounded parallelism with a semaphore
sem := make(chan struct{}, 8) // at most 8 at a time
for _, item := range items {
sem <- struct{}{} // acquire
wg.Go(func() {
defer func() { <-sem }() // release
process(item)
})
}
wg.Wait()
The golang.org/x/sync/errgroup package wraps this pattern with error propagation and cancellation:
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
for _, url := range urls {
g.Go(func() error { return fetch(ctx, url) })
}
if err := g.Wait(); err != nil { /* first error; ctx was cancelled for the rest */ }
Pipeline and fan-in
ctx := context.Background()
squares := Square(ctx, Generate(ctx, 1, 2, 3)) // stage -> stage
for v := range Merge(squares, otherStage) { // fan in
fmt.Println(v)
}
Timeout around any call
ch := make(chan result, 1) // buffered, so the goroutine can finish even if we stop waiting
go func() { ch <- doSlow() }()
select {
case r := <-ch:
use(r)
case <-time.After(time.Second):
return errTimeout
}
Rules that prevent most concurrency bugs:
- Know how every goroutine you start will end.
- The sender closes the channel, once.
- Pass
ctxand checkctx.Done()in loops and blocking operations. - Run tests with
-race.
Standard Library Quick Reference
JSON
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"` // omit empty string
CreatedAt time.Time `json:"created_at,omitzero"` // omit zero time (Go 1.24)
}
data, err := json.Marshal(u)
data, err := json.MarshalIndent(u, "", " ")
var u User
err := json.Unmarshal(data, &u)
// Streaming
err := json.NewDecoder(r.Body).Decode(&u)
err := json.NewEncoder(w).Encode(u)
// Unknown shape
var anyJSON map[string]any
Go 1.27 adds encoding/json/v2 and encoding/json/jsontext, a revised JSON API that, among other changes, rejects invalid UTF-8 and duplicate object keys by default. encoding/json (v1) keeps working.
Files and I/O
data, err := os.ReadFile("in.txt")
err = os.WriteFile("out.txt", data, 0o644)
f, err := os.Create("out.txt")
defer f.Close()
w := bufio.NewWriter(f)
defer w.Flush()
// Read line by line
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
}
if err := sc.Err(); err != nil {}
io.Copy(dst, src) // stream between Reader and Writer
os.MkdirAll("a/b/c", 0o755)
filepath.Join("dir", "file.txt") // OS-correct separators
filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error { return nil })
HTTP server (Go 1.22+ routing)
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"id": id})
})
mux.HandleFunc("POST /users", createUser)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second, // always set timeouts in production
}
log.Fatal(srv.ListenAndServe())
Graceful shutdown:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go srv.ListenAndServe()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx) // stops accepting, waits for in-flight requests
HTTP client
client := &http.Client{Timeout: 10 * time.Second} // the default client has no timeout
resp, err := client.Get("https://example.com")
if err != nil { return err }
defer resp.Body.Close() // always close the body
if resp.StatusCode != http.StatusOK { /* handle */ }
body, err := io.ReadAll(resp.Body)
Time
now := time.Now()
later := now.Add(90 * time.Minute)
d := later.Sub(now) // time.Duration
time.Since(start); time.Until(deadline)
now.Format(time.RFC3339) // "2006-01-02T15:04:05Z07:00"
now.Format("2006-01-02 15:04") // layout uses the reference time Mon Jan 2 15:04:05 MST 2006
t, err := time.Parse("2006-01-02", "2026-12-01")
time.Sleep(100 * time.Millisecond)
Logging (log/slog, Go 1.21)
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("user created", "id", 42, "email", "a@example.com")
slog.SetDefault(logger)
slog.Error("failed", "err", err)
Testing
// math_test.go, same package
package mathx
import "testing"
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"positive", 1, 2, 3},
{"negative", -1, -2, -3},
{"zero", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
}
})
}
}
func BenchmarkAdd(b *testing.B) {
for b.Loop() { // Go 1.24+; older code uses for i := 0; i < b.N; i++
Add(1, 2)
}
}
func FuzzReverse(f *testing.F) {
f.Add("hello")
f.Fuzz(func(t *testing.T, s string) {
if Reverse(Reverse(s)) != s {
t.Errorf("double reverse changed %q", s)
}
})
}
func ExampleAdd() {
fmt.Println(Add(1, 2))
// Output: 3
}
| Command | Does |
|---|---|
go test ./... |
All tests in the module |
go test -run TestAdd/negative ./... |
Tests matching a regex (subtests with /) |
go test -v |
Verbose |
go test -race |
With the race detector |
go test -cover / -coverprofile=c.out then go tool cover -html=c.out |
Coverage |
go test -bench . -benchmem |
Benchmarks with allocations |
go test -fuzz FuzzReverse |
Fuzzing |
go test -count=1 |
Disable test caching |
go test -short |
Skip tests that check testing.Short() |
Helpers: t.Helper() (better line numbers), t.Cleanup(fn), t.TempDir(), t.Setenv(), t.Parallel(), t.Context() (Go 1.24), t.Chdir() (Go 1.24), httptest.NewRecorder() / httptest.NewServer(), and testing/synctest (Go 1.25) for testing concurrent code with a fake clock.
Modules and Packages
go mod init github.com/you/project # creates go.mod
go get github.com/google/uuid@latest # add or upgrade a dependency
go get example.com/pkg@v1.2.3 # specific version
go get example.com/pkg@none # remove
go mod tidy # add missing, remove unused requirements
go list -m all # all dependencies
go list -m -u all # available upgrades
go mod why -m example.com/pkg # why is this needed?
go mod vendor # copy dependencies into vendor/
go install golang.org/x/tools/gopls@latest # install a binary
A typical go.mod:
module github.com/you/project
go 1.25
require (
github.com/google/uuid v1.6.0
)
tool golang.org/x/tools/cmd/stringer // Go 1.24: run with `go tool stringer`
| File / concept | Purpose |
|---|---|
go.mod |
Module path, Go version, dependencies |
go.sum |
Checksums: commit it |
go.work |
Workspace: develop several modules together (go work init ./a ./b) |
replace directive |
Point a dependency at a local path or fork |
internal/ folder |
Importable only from the parent tree: real encapsulation |
| Major versions v2+ | Module path ends in /v2 |
GOPROXY, GOPRIVATE |
Where modules are downloaded from; private repos |
Common project layout (start flat; add folders when needed):
project/
├── go.mod
├── main.go # or cmd/<app>/main.go for several binaries
├── internal/
│ ├── store/ # database code
│ └── api/ # HTTP handlers
└── pkg/ # optional: code meant for other modules
Package names: short, lowercase, no underscores, named for what they provide (store, not utils).
go Command Cheat Sheet
| Command | Purpose |
|---|---|
go run . |
Build and run |
go build ./... |
Compile everything |
GOOS=linux GOARCH=arm64 go build |
Cross-compile |
go build -ldflags="-s -w" |
Smaller binary (strip debug info) |
CGO_ENABLED=0 go build |
Static binary, no C toolchain |
go test ./... |
Test |
go vet ./... |
Static checks |
go fmt ./... |
Format |
go fix ./... |
Apply modernizers (rebuilt in Go 1.26) |
go doc fmt.Printf |
Documentation in the terminal |
go env / go env GOPATH |
Environment |
go version -m ./binary |
Module versions embedded in a binary |
go generate ./... |
Run //go:generate directives |
go clean -cache -testcache |
Clear caches |
go tool pprof cpu.out |
Profile analysis |
Linters worth adding: staticcheck and golangci-lint. gopls gives editors completion, rename and diagnostics.
Common Gotchas
| Gotcha | Explanation | Fix |
|---|---|---|
| Nil map write panics | var m map[string]int; m["a"] = 1 |
m := make(map[string]int) |
append aliasing |
Sub-slices share the backing array | slices.Clone, 3-index slice |
| Map iteration order | Random on purpose | Sort keys first |
| Nil interface vs nil pointer | An interface holding a typed nil pointer is not nil |
Return a literal nil for “no error” |
defer in a loop |
Defers run at function end, not per iteration | Move the body into a function |
Shadowing with := |
x, err := ... in an inner scope creates new variables |
Use = or rename; go vet -vettool shadow analyzers help |
| Goroutine leaks | Goroutine blocked forever on a channel nobody reads | Buffered result channels, ctx.Done() cases |
| Concurrent map access | Fatal error, not just a race | Mutex or sync.Map |
| Copying a mutex | Copies lock state | Pass pointers; go vet catches it |
| Range copies values | for _, v := range items { v.X = 1 } changes a copy |
for i := range items { items[i].X = 1 } |
time.After in hot loops |
Allocates a timer each call (collected since Go 1.23, but still work) | Reuse a time.Timer or use ctx |
| Integer overflow | Silent wraparound | Check bounds; math.MaxInt64 |
| String indexing | s[i] is a byte |
[]rune(s) or range s |
| HTTP response body | Not closing it leaks connections | defer resp.Body.Close() |
The nil-interface gotcha, in code:
type MyErr struct{}
func (*MyErr) Error() string { return "boom" }
func mayFail(fail bool) error {
var e *MyErr // typed nil pointer
if fail {
e = &MyErr{}
}
return e // BUG: returns a non-nil error interface even when fail is false
}
fmt.Println(mayFail(false) == nil) // false
Fix: if fail { return &MyErr{} }; return nil.
Go Version Feature Table
| Version | Released | Highlights |
|---|---|---|
| 1.18 | Mar 2022 | Generics, fuzzing, workspaces |
| 1.19 | Aug 2022 | Typed atomics, doc comment links |
| 1.20 | Feb 2023 | errors.Join, multiple %w, context.WithCancelCause |
| 1.21 | Aug 2023 | min, max, clear builtins; slices, maps, cmp, log/slog packages; sync.OnceValue |
| 1.22 | Feb 2024 | Per-iteration loop variables, range over int, ServeMux method and wildcard patterns, math/rand/v2 |
| 1.23 | Aug 2024 | Range over func iterators, iter package, unique package, timer changes |
| 1.24 | Feb 2025 | Generic type aliases, tool directives in go.mod, b.Loop, t.Context, omitzero, os.Root, Swiss-table maps |
| 1.25 | Aug 2025 | sync.WaitGroup.Go, testing/synctest, container-aware GOMAXPROCS |
| 1.26 | Feb 2026 | new(expr), Green Tea garbage collector on by default, rebuilt go fix modernizers, crypto/hpke |
| 1.27 | Aug 2026 | Generic methods, encoding/json/v2, crypto/mldsa |
Each Go release is supported until two newer major releases exist, so as of December 2026 Go 1.26 and 1.27 receive security fixes.
Resources
- A Tour of Go: interactive basics.
- Effective Go: idioms (older, still useful).
- Go by Example: annotated example programs.
- The Go Programming Language Specification
- Go standard library docs
- Go Blog: in-depth articles on features like iterators and generics.
- Go Code Review Comments: common review feedback.
- Go release notes
- Go Playground: run snippets in the browser.
Which Concurrency Tool When
| Problem | Reach for | Why |
|---|---|---|
| Wait for N goroutines | sync.WaitGroup (wg.Go) |
Simplest join |
| Wait for N goroutines and stop on the first error | errgroup.Group |
Error propagation + context cancellation |
| Limit how many run at once | Buffered channel semaphore or errgroup.SetLimit |
Bounded parallelism |
| Protect a map or struct shared by goroutines | sync.Mutex / sync.RWMutex |
Clear ownership of data |
| A counter or flag hit from many goroutines | atomic.Int64, atomic.Bool |
No lock, cheap |
| Pass ownership of data between stages | Channels | “Share memory by communicating” |
| Cancel work, timeouts, deadlines | context.Context |
Propagates through APIs |
| Run initialization once | sync.Once, sync.OnceValue |
Safe lazy init |
| Reuse short-lived buffers in hot paths | sync.Pool |
Fewer allocations |
| Periodic work | time.Ticker in a select loop |
Stoppable with ctx |
Go vs Other Languages: Translation Table
| Concept | Go | Python | JavaScript / TypeScript | Java |
|---|---|---|---|---|
| Error handling | if err != nil { return err } |
try/except |
try/catch, rejected promises |
Checked exceptions |
| Concurrency | Goroutines + channels | asyncio, threads |
Event loop + promises | Threads, virtual threads |
| Dynamic array | []T slice |
list |
Array |
ArrayList<T> |
| Hash map | map[K]V |
dict |
Map, object |
HashMap<K,V> |
| Set | map[T]struct{} |
set |
Set |
HashSet<T> |
| Interface | Implicit | Duck typing / Protocol |
Structural types | Explicit implements |
| Inheritance | Embedding (composition) | Classes | Classes / prototypes | Classes |
| Generics | Type parameters (1.18+) | Type hints only | TS generics (compile time) | Generics (erased) |
| Package manager | go mod |
pip / uv | npm / pnpm | Maven / Gradle |
| Formatter | gofmt (built in) |
Black / Ruff | Prettier | various |
| Build output | Single static binary | Interpreter + source | Runtime + bundle | JVM + JAR |
null |
nil (typed) |
None |
null / undefined |
null |
FAQ
Is Go hard to learn? No. The language is small (the spec is short enough to read in an afternoon), and most people are productive within a week. The harder parts are idioms: error handling, designing small interfaces and writing correct concurrent code.
Should I learn Go or Rust? Go if you want to ship network services, CLIs and infrastructure tools quickly with a garbage collector and very fast builds. Rust if you need no GC pauses, maximum performance, or memory safety in systems code, and accept a steeper learning curve. Many teams use both.
What is Go used for? Cloud and infrastructure software (Docker, Kubernetes, Terraform, Prometheus are written in Go), web APIs and microservices, CLIs, networking and DevOps tooling.
Does Go have exceptions?
No. Errors are ordinary return values. panic exists but is reserved for bugs and unrecoverable states.
Is Go object-oriented? It has types with methods, interfaces and composition through embedding, but no classes and no inheritance.
Why does Go not have a ternary operator?
The Go authors chose to keep a single way to write conditionals. Use an if statement, or cmp.Or for “first non-zero value” defaults.
How do I handle nil pointer panics?
Check for nil before dereferencing values that can be absent, return (value, ok) or (value, error) instead of nil pointers when you can, and make zero values useful.
How many goroutines can I start? Hundreds of thousands are fine on ordinary hardware, since each starts with a small stack. The real limits are what the goroutines do (open sockets, memory they hold) and the systems they call, so bound concurrency against external resources.
What is the difference between a buffered and an unbuffered channel? An unbuffered send waits until a receiver takes the value (a synchronization point). A buffered channel lets senders continue until the buffer is full. Use buffers to decouple bursts, not to hide synchronization bugs.
How do I read environment variables and flags?
os.Getenv("PORT"), os.LookupEnv (tells you whether it was set), and the flag package: port := flag.Int("port", 8080, "listen port"); flag.Parse().
What is the internal folder?
Packages under internal/ can only be imported by code rooted at the parent of internal. It is the compiler-enforced way to keep APIs private.
Which web framework should I use?
Start with the standard library: net/http with the Go 1.22 router covers method and path-parameter routing. Popular frameworks include Gin, Echo, Chi (a lightweight router compatible with net/http) and Fiber (built on fasthttp, not net/http).
Where to Go Next
- Do A Tour of Go end to end, then read this cheat sheet again: it will make more sense.
- Build something real: a CLI with
flagandos, then a JSON API withnet/httpanddatabase/sql(or pgx for PostgreSQL). - Learn the tools:
go test -race,pprof, staticcheck, golangci-lint. - Read the Go blog posts on concurrency patterns, error handling and range over func.
- Read real code: the standard library source (
go doc -src), and well-known Go projects like Kubernetes or Hugo.
Contributing
PRs welcome. Keep entries accurate and mark features newer than Go 1.21 with the version that introduced them. New code examples go in examples/ with tests, and go vet ./... && go test -race ./... must pass.
License
MIT. See LICENSE.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.