Go Cheatsheet — Quick Reference
A Go 1.22 reference for syntax, types, goroutines, and the most-used standard library packages — about 80% of day-to-day needs.
Go Go 1.22
Go (gc toolchain) · Compiled · Concurrent · Imperative · Static · Strongly typed · Structural (interfaces)
Recommended Learning Path
Start with go run / go build and go.mod → learn variables, types, and control flow → go deeper on functions, pointers, and structs → organize data with slices and maps → understand interfaces and error handling → write concurrency with goroutines and channels → then learn http, context, time, and build/testing as needed. The FAQ section is a great place to come back when you hit footguns.
1.Hello World & Build Environment
Run Go programs, manage go.mod modules, and use the toolchain.
Minimal program
Every program starts at package main with a func main entry point. Use fmt for output.
Run and build
go run compiles and runs; go build produces an executable; go install puts it on $GOBIN.
go.mod modules
go.mod declares the module path and dependencies. go mod init bootstraps it; go mod tidy cleans up.
Packages and imports
import brings in standard library and third-party packages. Files in the same directory share a package. Unused imports fail to compile.
Formatted output
fmt.Println/Printf/Print are the workhorses. Printf uses verbs like %s %d %v. Sprintf returns the formatted string.
Arguments and input
os.Args holds command-line arguments, the flag package parses them, and fmt.Scan reads interactive input.
Multi-file programs
Multiple .go files in the same directory belong to the same package and can call each other directly; they share package scope.
Toolchain
go version shows the version, go env lists the environment, go doc shows documentation, and go fmt formats the code.
2.Variables & Constants
Variable declarations, short declarations, constants, zero values, and type conversions.
Variable declarations
Use var to declare variables; the type comes after the name. You must initialize the value or accept the zero value.
Short variable declarations
:= declares and initializes with type inference. It works only inside functions, and at least one variable on the left must be new.
Constants
const declares values fixed at compile time. iota produces auto-incremented enumerations. Constants have arbitrary precision.
Zero values
An uninitialized variable has a zero value: 0 for numbers, "" for strings, false for booleans, nil for pointers. Zero values are usable out of the box.
Multiple assignment
Assign multiple variables on one line, swap values, and unpack multi-return function calls.
Scope
Block scope: variables are visible only inside their block. Watch out for shadowing. Package-level variables exist once per package.
Type conversion
T(x) performs an explicit conversion. Go never auto-converts numeric types; conversions can overflow or truncate.
Naming conventions
Identifiers starting with an uppercase letter are exported across packages; lowercase ones stay package-private. Use camelCase and short names for locals.
3.Data Types
Built-in types, structs, arrays, interfaces, and generics.
Basic types
bool, string, integers, floats, complex numbers, and the byte/rune aliases.
Numeric operations
Arithmetic, bitwise operators, and the math package. Integer division truncates. Watch for overflow.
struct
A struct composes fields. Initialize by name or positionally; use struct tags for metadata.
Arrays
Arrays have a fixed length and behave as value types (they are copied). You rarely use them directly — most code uses slices.
type definitions
type defines a new type or an alias. A defined type is distinct from its underlying type and needs explicit conversion.
Generics
Generic functions use [T any] type parameters. Constraints (often interfaces) restrict the set of allowed types.
interface types
An interface is a method set. The empty interface interface{} (any) holds any value.
comparable constraints
comparable is a built-in constraint for types that support ==. Used for map keys and generic comparisons.
4.Pointers
Pointers and address operations: take address, dereference, new/make, stack vs heap.
Address-of &
& takes the address of a variable and returns a pointer that refers to that memory location.
Dereference *
*p accesses the value pointed to by p. Struct fields through a pointer auto-dereference.
nil pointers
A nil pointer is the zero value. Dereferencing one panics — check for nil before use.
Pointer parameters
A pointer parameter lets a function mutate the caller's variable. Value parameters work on a copy. Large structs should be passed by pointer to avoid copying.
new and make
new allocates a value type and returns a pointer to it. make initializes slices, maps, and channels and returns a ready-to-use value.
Pointer idioms
Pointers share mutable state. Return a pointer or value depending on the semantics; pick method receivers consistently.
Stack and heap
The compiler decides whether a variable lives on the stack or the heap. Taking the address may cause escape to the heap.
Pointer safety
Go pointers have no arithmetic (no C-style p+1). The GC manages lifetimes, so there are no dangling pointers.
5.Control Flow
if, for, switch, defer, and loop control.
if / else
if conditions don't use parentheses. You can write a short init statement before the condition. Conditions must be boolean.
for loops
Go has only the for loop. Use the C-style three-clause form, a while-style condition, or an infinite loop.
range iteration
range iterates over arrays, slices, maps, strings, and channels. Since Go 1.22, loop variables are scoped per iteration.
switch
switch does not fall through by default. Cases can list multiple values, omit the expression (if-else chain), or do a type switch.
defer
defer schedules a call to run when the surrounding function returns. Defers run in LIFO order — perfect for cleanup.
break and continue
break exits the loop, continue skips to the next iteration. Both accept labels to control nested loops.
switch with init
switch can take an init statement before the expression. Useful for the error-handling chain idiom.
goto and labels
goto jumps to a label. Go allows it but uses rarely; deep error-handling code is the one common case.
6.Functions
Function definitions, multiple return values, closures, methods, function values.
Function definitions
func defines a function. Parameters take their types; the return type comes last.
Multiple return values
Go functions can return multiple values. The idiom is (value, error).
Named return values
Return values can be named. Assign to them in the body and use a bare return to send them out.
Variadic parameters
...T gathers any number of arguments into a slice. Use slice... to spread one on a call.
Closures
Closures capture surrounding variables. A returned function keeps its own state. Since 1.22, loop variables are captured per iteration.
Methods
Methods attach to a receiver, which appears between func and the method name.
Function values
Functions are first-class values — assign them, pass them as arguments, return them. A function type is its signature.
init functions
init functions run automatically when a package is loaded. Each file may contain multiple init functions for setup.
7.Strings
Immutable strings, rune/byte, the strings package, and formatting.
String basics
A string is an immutable byte sequence. Use double-quoted literals for interpreted strings and backticks for raw strings.
rune and characters
A rune is a Unicode code point (int32). range iterates by rune; the unicode/utf8 package decodes bytes.
strings.Builder
Builder efficiently accumulates strings. Avoid the + chain in loops — Builder reduces allocations.
The strings package
Contains, Split, Join, Trim, Replace, and many more string operations in the strings package.
fmt formatting
Printf/Sprintf use verbs, with width, precision, and padding. Fprintf writes to any io.Writer.
strconv conversion
Convert strings to/from numbers and booleans. Handle quote and unquote too.
Encoding/decoding
Base64, hex, and URL encoding. Convert between []byte and string as needed.
Character iteration
Iterate strings by rune to handle non-ASCII text. Be aware that string indices are byte offsets.
8.Collections
Slices, maps, arrays, and sorting.
Slices
A slice is a dynamic view over a backing array. A nil slice is length 0 and usable with append.
Slice operations
Use append to grow, copy to duplicate, and idioms on top of them to insert or remove elements.
make and capacity
make creates a slice and pre-allocates capacity. Pre-allocating avoids repeated reallocations during append.
map
Maps store key/value pairs. Create with make, read, write, delete with delete, iterate with range. A nil map is read-only.
map idioms
Use maps as sets, counters, and caches. Great for collecting keyed values.
Sorting
The sort package sorts slices. Pass a custom comparator; use sort.Search for binary search.
The container package
container/heap for heaps and container/list for doubly-linked lists. Use them when you need these data structures.
Iteration tricks
range gives you indices and/or values. Sort map keys when a deterministic order matters.
9.Memory & Performance
Garbage collection, escape analysis, allocation optimization, and memory profiling.
Garbage collection
Go has an automatic, concurrent, low-pause GC. You never call free manually — the runtime manages memory.
Escape analysis
The compiler decides where a variable lives. Taking its address, closing over it, or boxing it into an interface may escape it to the heap.
Allocation optimization
Pre-allocate capacity, reuse buffers, and reduce small allocations on hot paths.
Finalizers
runtime.SetFinalizer runs a hook before an object is reclaimed — useful as a safety net for external resources.
Memory model
In concurrent code, writes are only guaranteed visible to other goroutines after a synchronization event: channel, mutex, or atomic.
Memory profiling
pprof profiles memory and CPU. Heap snapshots help you find leaks.
sync.Pool
Pool reuses short-lived objects to ease GC pressure — great for buffers and decoders.
Stack and recursion
goroutine stacks grow dynamically. Deep recursion is limited; rewrite very deep recursion as a loop.
10.Structs & Methods
Go's OOP: structs, interfaces, embedding, and composition (no class inheritance).
structs and methods
Structs hold data; methods bind behavior to a type. Use constructor functions for clarity.
Choosing a receiver
Value receivers don't mutate; pointer receivers do. Keep all methods of a type using the same receiver kind.
Interfaces
An interface is a behavioral contract. A type satisfies it implicitly if its method set matches.
Interfaces and nil
A nil interface is different from an interface holding a typed nil pointer. Be careful when checking for nil.
Embedding
An embedded struct (or interface) promotes its fields and methods. Prefer composition over inheritance.
Composition
Go favors composition over inheritance. Compose small interfaces to build larger ones.
Type assertions
Assert an interface back to a concrete type. Use the ok form to stay safe; type switch handles multiple cases.
any / empty interface
any (alias for interface{}) holds any value. Recover the concrete type with an assertion or a type switch.
11.Error Handling
The error interface, error wrapping, errors.Is/As, panic/recover.
The error interface
error is a built-in interface with a single method, Error() string. Functions return errors — there are no exceptions.
Returning errors
Errors bubble up the call stack. Check err != nil at each step and handle or wrap it.
Error messages
fmt.Errorf builds a formatted error; errors.New constructs a plain one. Use %w to wrap an underlying error.
errors.Is
errors.Is walks the error chain looking for a match. Prefer it over err == sentinel checks.
errors.As
errors.As walks the chain and assigns the first error matching the target type.
panic and recover
panic aborts the goroutine; recover (only inside a deferred call) catches it. Reserve for unrecoverable situations.
Error handling in defer
Use a named return value so a deferred function can assign a close error back to it.
Joining errors
errors.Join combines multiple errors into one. Useful for validating many fields or steps at once.
12.Input / Output
File I/O, bufio, JSON, io.Reader/Writer.
Reading files
Use os.ReadFile for small files. For large files, os.Open plus a Reader (such as bufio.Scanner) streams line by line.
Writing files
Use os.WriteFile to overwrite atomically, os.OpenFile to append, and bufio.Writer to batch writes.
JSON marshaling
json.Marshal encodes structs to JSON. Use struct tags to control field names and options.
JSON unmarshaling
json.Unmarshal parses JSON into a struct or map. json.NewDecoder streams large payloads.
io.Reader / Writer
io.Reader and io.Writer abstract streams. io.ReadAll and io.Copy are the convenience helpers.
bufio buffering
bufio wraps a Reader or Writer with a buffer to reduce syscalls. Scanner makes line iteration easy.
Standard streams
os.Stdin/Stdout/Stderr are the standard streams. fmt.Scan, fmt.Scanf, and bufio.Scanner cover most input needs.
Path operations
filepath handles paths portably. Join, Dir, Base, and Ext are the everyday helpers.
13.Common Pitfalls
The most common Go footguns and the correct idioms.
nil vs empty slice
A nil slice and an empty slice are different — JSON marshals nil as null and empty as []. Be explicit with make.
Loop variable capture
Before Go 1.22, goroutines closing over a loop variable shared it. Since 1.22, each iteration gets its own variable.
Maps iterate in random order
Map iteration order is randomized. Sort the keys if you need a deterministic order.
Mutating strings
Strings are immutable. Convert to []byte (for ASCII) or []rune (for text), edit, and convert back.
Slice copying and sharing
Assigning a slice shares its backing array. Use copy (or a full-slice append) to make an independent one.
Ignoring errors
Ignoring err returns silently breaks. Handle it, log it, or assign to _ to make the intent explicit.
Inconsistent receivers
Mixing value and pointer receivers on the same type leads to subtle interface-satisfaction issues. Pick one.
Variable shadowing
:= in an inner scope creates a new variable, shadowing the outer one. Be explicit with = when you want reuse.
defer in loops
A defer in a loop only fires when the surrounding function returns. Wrap each iteration in a helper to release resources promptly.
14.Concurrency
goroutines, channels, select, and concurrency safety.
goroutine
The go keyword starts a concurrent function call. Goroutines are cheap with growable stacks; when main exits the program ends.
channel
A channel is a typed conduit for goroutine communication. An unbuffered channel blocks send until a receive is ready and vice versa.
Buffered channels
make(chan T, n) creates a buffered channel. Sends block only when full, receives only when empty.
select
select waits on multiple channel operations. If several are ready, one is chosen at random; default runs immediately when none are.
WaitGroup
sync.WaitGroup waits for a group of goroutines. Call Add before starting, Done (via defer) when finished, Wait to block.
Mutex
sync.Mutex protects shared state with Lock/Unlock. Use sync.RWMutex when reads dominate writes.
sync.Once
sync.Once guarantees a function runs at most once, even under concurrent calls. Great for lazy singletons.
Data race detector
go run -race (or go test -race) detects unsynchronized concurrent accesses to the same memory.
15.Networking
HTTP requests, servers, context, and TCP.
HTTP GET
http.Get issues a GET. Always close resp.Body (typically with defer) and check the status code.
HTTP server
http.HandleFunc registers a handler; ListenAndServe starts the server. Use a custom *http.Server for graceful shutdown.
HTTP client
Use http.Client to set timeouts and connection-pool options. http.NewRequest lets you customize method, headers, and body.
JSON API
Decode JSON responses into typed structs. Use tags to map API field names to Go fields.
context
context carries cancellation and deadlines across calls. WithTimeout/WithCancel derive child contexts; thread it through I/O.
URL parsing
url.Parse splits a URL into scheme, host, path, query, and fragment. Build URLs with url.Values.Encode.
TCP socket
net.Dial connects a client; net.Listen accepts on the server side. The connection is an io.ReadWriteCloser over raw bytes.
Routing enhancements
Since Go 1.22, http.ServeMux supports method matching (GET /path), path parameters ({id}), and wildcards.
16.Time & Date
The time package, Duration, formatting, and time zones.
Getting time
time.Now returns the current Time. Read its components; convert to UTC or Local with .UTC() / .In(loc).
Duration
time.Duration is an int64 count of nanoseconds. Use named unit constants (time.Second, etc.) and add/subtract freely.
Formatting
Time.Format uses a reference layout — Mon Jan 2 15:04:05 MST 2006 — to describe the desired format.
Parsing
time.Parse parses a string into Time using the same reference layout as Format. Use time.ParseInLocation for a specific zone.
Ticker
time.Ticker fires on a fixed interval. Stop it (with defer) when done to release resources.
Sleep and waiting
time.Sleep blocks the calling goroutine for the given duration. Use Timer/After for cancellable delays.
Timer
time.Timer fires once after a delay. Stop or Reset it; combine with select for cancellation.
Time zones
Load IANA zones with time.LoadLocation, convert a Time with .In(loc), or build a fixed-offset zone with time.FixedZone.
17.Process & Environment
Command-line arguments, environment variables, subprocesses, and exit codes.
Command-line arguments
os.Args is the slice of command-line arguments. os.Args[0] is the program path; the rest follow.
flag parsing
The flag package parses command-line flags. Define defaults, parse, then read the values.
Environment variables
os.Getenv reads, os.Setenv sets, and os.LookupEnv distinguishes "unset" from "empty". os.Environ lists them all.
Exit codes
os.Exit terminates immediately with the given status. 0 means success, non-zero means failure. Defers don't run.
Running subprocesses
exec.Command runs an external program. Capture stdout/stderr, pipe stdin, or set environment variables.
Signal handling
signal.Notify delivers OS signals to a channel. Handle SIGINT/SIGTERM for graceful shutdown.
File system
Create directories with MkdirAll, remove trees with RemoveAll, rename with Rename, and inspect with Stat.
Working directory
Read the working directory with os.Getwd, change it with os.Chdir, and turn relatives into absolutes with filepath.Abs.
18.Regular Expressions
The regexp package: compile, match, find, replace, and capture groups.
Compile
Use regexp.Compile to handle the error, or regexp.MustCompile when you want a panic on failure (typical at package scope).
Match test
MatchString tests whether a pattern matches (or matches fully with ^...$). Match works on []byte.
Find
FindString returns the first match. FindStringIndex returns the start/end byte offsets.
Find all
FindAllString returns all matches; pass -1 (or omit) to get all, or an integer to cap the count.
Replace
ReplaceAllString substitutes every match. Use $1, $2 in the replacement to refer to capture groups.
Split
re.Split slices a string around matches of the regex. -1 means no limit.
Capture groups
Parentheses capture sub-matches. FindStringSubmatch returns them; named groups (P<name>) look them up by name.
Common patterns
Common patterns (email, URL, IP, phone) plus the core syntax: classes \d\w\s, quantifiers +*?, and anchors ^$.
19.Build & Test
Building, unit testing, static analysis, and cross-platform compilation.
go build
go build compiles a package. Use -o for the output path, -tags for build tags, and -ldflags for size/info tweaks.
Unit testing
go test runs *_test.go files. Use t.Error/t.Errorf for non-fatal checks and t.Fatal/t.Fataliff to stop a test.
Benchmarking
go test -bench runs Benchmark functions. The framework loops b.N times to measure per-op cost.
Static analysis
go vet catches common mistakes (printf mismatches, bad locks, etc.). Run it in CI alongside the build.
Formatting
gofmt is the canonical formatter. goimports adds automatic import management on top of it.
Cross-compilation
Set GOOS and GOARCH before go build to cross-compile. CGO must be off or you need a cross C toolchain.
Race detector
go build -race (or go test -race) instruments the binary so the runtime reports data races as they happen.
Module versions
go.mod pins versions, go get updates them, replace directs a module to a fork/local path, and go.sum hashes them for integrity.
CI integration
A typical CI run checks format, runs go vet, executes go test -race -cover, then builds and publishes artifacts.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained Go 1.22 cheatsheet that covers the language core and the most-used parts of the standard library — roughly 80% of what real projects need. It favours modern idioms: short variable declarations, structured error handling with errors.Is / errors.As, generics, and (since 1.22) per-iteration loop variables. For authoritative reference see the official Go tutorial and Effective Go. The 19 sections each focus on one topic — from your first program to goroutines, interfaces, and common pitfalls. Each section splits into 8–14 short sub-topics (5–20 lines of code each) for about 150 topics in total. Code samples are intentionally short and self-explanatory. Everything happens in your browser — no uploads, no tracking. This page is part of GuruToolkit's free developer tool collection; the snippets here are free to use, with no warranty of any kind.
Version 2.1.0