Go (Golang) Cheatsheet

Go language quick reference: variables, functions, structs, goroutines, channels, and error handling

The Go cheatsheet covers variables, functions, structs, interfaces, goroutines, channels, error handling, slices, and maps. Focuses on Go idioms that trip up newcomers from other languages.

How to Use This Go Cheatsheet

Go (Golang) is a statically typed, compiled language designed for simplicity and concurrency. This cheatsheet covers the most common patterns with a focus on idioms that differentiate Go from Python, Java, or JavaScript.

Error Handling Pattern

Go returns errors as values. The convention is result, err := doSomething() followed by if err != nil { return err }. This makes error handling explicit and visible. Use fmt.Errorf("context: %w", err) to wrap errors with context.

Goroutines and Channels

Launch a goroutine with go func(). Communicate between goroutines via channels: ch := make(chan int). Use select to wait on multiple channels. Use buffered channels make(chan int, 10) to avoid blocking.

defer, panic, recover

defer runs a function when the surrounding function returns — perfect for cleanup. panic is like an exception; use it only for truly unrecoverable errors. recover() inside a deferred function catches panics.

Frequently Asked Questions

Is this Go cheatsheet free?

Yes, completely free with no signup. Copy any example with one click.

What makes Go error handling different from other languages?

Go uses explicit error return values instead of exceptions. Functions return (result, error) and callers must check if err != nil. This makes error handling visible in code flow, unlike try/catch which can hide control flow. The errors.Is() and errors.As() functions handle wrapped errors.

What is the difference between a goroutine and a thread?

Goroutines are Go's lightweight concurrency primitives. They start with a tiny stack (2-8KB) that grows as needed, vs OS threads which have fixed 1-8MB stacks. Go's runtime scheduler multiplexes thousands of goroutines onto a small number of OS threads (M:N threading). You can run millions of goroutines on a single machine.

When should I use channels vs mutexes in Go?

Channels: for communicating data between goroutines and signaling events — follow 'communicate by sharing' idiom. Mutexes (sync.Mutex): for protecting shared state that multiple goroutines read/write. Rule of thumb: use channels for coordination, mutexes for protecting data structures.

What is the difference between var and := in Go?

var declares with explicit type and is valid at package level. := is short variable declaration (infers type) and only works inside functions. Both create new variables. var name string = '' vs name := '' — the := version infers string type automatically.