Go Cheat Sheet
Go syntax, goroutines, channels, error handling, and package structure for writing concurrent, statically typed programs.
2 PagesIntermediateApr 5, 2026
Basic Syntax
Variables, control flow, and printing.
go
package mainimport "fmt"func main() { age := 30 // short variable declaration name := "Ada" var pi float64 = 3.14159 if age >= 18 { fmt.Println(name, "is an adult") } for i := 0; i < 5; i++ { fmt.Println("Count:", i) }}
Goroutines & Channels
Concurrency primitives built into the language.
go
func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { results <- j * 2 }}func main() { jobs := make(chan int, 5) results := make(chan int, 5) go worker(1, jobs, results) // launch goroutine for i := 1; i <= 5; i++ { jobs <- i } close(jobs) for i := 0; i < 5; i++ { fmt.Println(<-results) }}
Error Handling
Idiomatic multi-value error returns.
go
func divide(a, b float64) (float64, error) { if b == 0 { return 0, fmt.Errorf("cannot divide %f by zero", a) } return a / b, nil}func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Result:", result)}
Core Keywords
Common Go language keywords.
- go- starts a new goroutine to run a function concurrently
- chan- typed channel used to communicate between goroutines
- defer- schedules a call to run when the surrounding function returns
- interface{}/any- represents a value of any type
- struct- composite type grouping named fields
- select- waits on multiple channel operations
- panic/recover- unwind the stack on fatal errors and optionally recover
- :=- short variable declaration with type inference
Generics
Type parameters with constraints (Go 1.18+).
go
type Number interface { ~int | ~int64 | ~float64}func Sum[T Number](nums []T) T { var total T for _, n := range nums { total += n } return total}func Map[T, U any](s []T, f func(T) U) []U { r := make([]U, len(s)) for i, v := range s { r[i] = f(v) } return r}fmt.Println(Sum([]int{1, 2, 3})) // 6
Context for Cancellation
Propagate deadlines and cancellation across goroutines.
go
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()select {case <-time.After(5 * time.Second): fmt.Println("work done")case <-ctx.Done(): fmt.Println("cancelled:", ctx.Err()) // context deadline exceeded}// Pass values (use sparingly, request-scoped only)ctx = context.WithValue(ctx, "reqID", "abc123")
Sync Primitives
WaitGroup, Mutex, and Once for coordinating goroutines.
go
var wg sync.WaitGroupvar mu sync.Mutexcount := 0for i := 0; i < 5; i++ { wg.Add(1) go func() { defer wg.Done() mu.Lock() count++ mu.Unlock() }()}wg.Wait()var once sync.Onceonce.Do(func() { fmt.Println("runs once") })
Essential Standard Library
Frequently used packages from the standard library.
- fmt- formatted I/O with Printf, Sprintf, Errorf verbs
- strings- string manipulation: Split, Join, Contains, Builder
- strconv- conversions between strings and numbers (Atoi, Itoa)
- encoding/json- Marshal/Unmarshal structs to and from JSON
- net/http- HTTP client and server implementation
- io- Reader/Writer interfaces and copy utilities
- errors- Is, As, Unwrap for wrapped error inspection
- sort- Slice, Search, and Stable sorting helpers
Pro Tip
Use `go vet` and `-race` (go run -race ./...) during development to catch suspicious code and data races before they hit production.
Was this cheat sheet helpful?
Explore Topics
#Go#GoCheatSheet#Programming#Intermediate#BasicSyntax#GoroutinesChannels#ErrorHandling#CoreKeywords#Concurrency#CheatSheet#SkillVeris