The Go standard library, learnable in an afternoon.
A tour of every public stdlib package — what it's for, when to reach for it, the shape of the API, and the gotchas. Hand-written for the packages you'll actually use; auto-generated reference for the rest. 170 packages covered.
Start here
If you're new to Go, learn these in this order. They cover almost everything a real program needs.
- 1 fmt Print things, format strings, build error messages. Try: Print a struct three ways with %v, %+v, %#v.
- 2 errors Idiomatic error handling — sentinels, wrapping, Is/As. Try: Wrap an error with fmt.Errorf %w and check it with errors.Is.
- 3 strings Read, search, and reshape UTF-8 text. Try: Use strings.Builder to assemble a CSV row.
- 4 strconv Parse "42" into an int and back. Try: Read a number from the command line with Atoi.
- 5 os Files, env vars, args, exit codes. Try: Read a file with os.ReadFile and print its size.
- 6 io Streams: Reader/Writer interfaces glue everything. Try: Pipe a file into stdout with io.Copy.
- 7 bufio Read a file or stdin one line at a time. Try: Count lines in a file with bufio.Scanner.
- 8 encoding/json Encode/decode Go values as JSON. Try: Round-trip a struct: Marshal, then Unmarshal back.
- 9 time Wall time, durations, sleep, format/parse. Try: Format time.Now() as RFC3339; parse it back.
- 10 context Cancellation and deadlines through your call graph. Try: Run a slow function with a 1-second WithTimeout.
- 11 net/http HTTP client + server in one package. Try: Build a server that responds "hello, {name}" using path values.
- 12 testing Write tests, benchmarks, and table-driven cases. Try: Write a TestX with t.Run subtests over a table.
- 13 slices Generic slice helpers — sort, search, transform. Try: Sort a []User by Age with slices.SortFunc and cmp.Compare.
- 14 log/slog Structured logging in the stdlib. Try: Log a request with slog.Info("req", "method", m, "path", p).
Browse by category
170 hand-written guides · 0 auto-generated overviews. Packages flagged deprecated, insecure, or frozen are clearly marked.
Formatting & Strings
bytes
The strings package, but for []byte. Plus Buffer (a mutable growable byte buffer) and NewReader.
fmt
Formatted I/O: Print, Printf, Sprintf, Scan, Errorf. Go's go-to for building and parsing text.
regexp
RE2 regular expressions. Guaranteed linear time — no catastrophic backtracking.
regexp/syntax
Parse a regular expression into an AST. Needed only if you're building tooling on top of regex syntax.
strconv
Convert between strings and numeric/boolean types. Lower-level and faster than fmt for pure conversion.
strings
Search, split, join, replace, case conversion. Works on UTF-8-encoded strings.
text/scanner
A Go-style tokenizer: idents, numbers, strings, comments. Great for building mini-languages and config parsers.
text/tabwriter
Aligned columns in plain text. Feed it tab-separated lines; it pads so columns line up.
unicode
Rune classification and simple case conversion. The 'is this a letter / digit / space' answers.
unicode/utf16
Encode and decode UTF-16 (surrogate pairs). Rarely needed in Go — mostly useful when crossing into Windows APIs or JS.
unicode/utf8
Work with UTF-8-encoded strings at the rune level: counts, encoding, decoding, validation.
I/O & Files
bufio
Buffered I/O on top of io.Reader/Writer. Adds line-reading, large single reads, and a fluent Scanner.
embed
Embed files and directories into your binary at build time. No external assets at runtime.
io
The Reader/Writer interfaces every streaming API is built on — and the helpers to copy, limit, tee, and combine them.
io/fs
The abstract filesystem interface. Lets one code path work over disk, embed.FS, a zip, a test double, or anything else.
os
Portable OS interface: files, env, args, signals, processes.
path
Slash-separated path manipulation. For URLs and io/fs paths. NOT for OS files — use path/filepath for that.
path/filepath
OS-aware path manipulation and directory walking. Use this for filesystem paths, not path (which is URL-style).
Time & Context
Concurrency
Collections
cmp
Generic comparison helpers (Go 1.21+). The glue between the old world and slices.SortFunc / maps / binary search.
iter
Defines Seq and Seq2, the types behind range-over-func (Go 1.23+). Write reusable iterators for any collection.
maps
Generic map operations (Go 1.21+). The missing helpers for Go's built-in map type.
slices
Generic slice operations (Go 1.21+). The modern answer to 'does stdlib have a Contains?' — yes.
sort
Sorting for slices and any sort.Interface. For generic slice sorting prefer the newer slices package.
Encoding
encoding
The shared interfaces every encoding package honors: BinaryMarshaler, TextMarshaler, and their Unmarshaler pairs.
encoding/ascii85
Ascii85 (aka btoa) — 4 bytes become 5 printable chars. More compact than base64, much rarer.
encoding/asn1
ASN.1 DER encoding — the format certificates, private keys, and X.509 structures live in. Reach for this when interoperating with PKI.
encoding/base32
Base32 encoding. Same API shape as encoding/base64 — pick base32 when you need case-insensitive output (e.g., TOTP secrets, some filenames).
encoding/base64
Base64 encoding. Standard, URL-safe, with or without padding — four ready-made encodings.
encoding/binary
Read and write fixed-size binary numbers. Big-endian, little-endian, and variable-length (varint).
encoding/csv
Read and write RFC 4180 CSV. Streaming, configurable delimiter, quote-aware.
encoding/gob
Go-native binary serialization. Self-describing, concise, Go-to-Go only. Not a cross-language format.
encoding/hex
Hex encoding: []byte ↔ ASCII hex string.
encoding/json
Encode and decode JSON. Works with structs via reflection and tags, or maps/any for dynamic shapes.
encoding/json/jsontext
Low-level JSON tokenizer/emitter that underpins encoding/json/v2. Stream JSON without building a tree, with precise control over formatting.
encoding/json/v2
Rewrite of encoding/json (experimental in Go 1.25, GOEXPERIMENT=jsonv2). Faster, stricter, configurable. Opt-in.
encoding/pem
The BEGIN/END block format for certificates and keys. Thin layer over base64 with a typed header.
encoding/xml
XML encode/decode via reflection and struct tags. Same model as encoding/json.
Hashing
hash
The Hash interface every hash algorithm in stdlib implements. A growable io.Writer that produces a fixed-size digest.
hash/adler32
Adler-32 checksum. Used inside zlib. Very fast; weaker than CRC-32 for short inputs.
hash/crc32
CRC-32 checksums. Fast, 32-bit, great for integrity checks — not a secure hash.
hash/crc64
CRC-64 checksums. Same shape as crc32 with a 64-bit digest.
hash/fnv
Fowler–Noll–Vo non-cryptographic hash. Very simple, decent distribution — good for hash tables and bloom filters.
hash/maphash
Fast, randomly-seeded hashing for strings and bytes. The same hash Go's map uses internally — great for building sharded caches.
Networking
mime
MIME types: look up by extension, parse Content-Type parameters, and encode/decode RFC 2047 encoded-words.
mime/multipart
Read and write multipart messages — file uploads, email parts.
mime/quotedprintable
Quoted-printable encoding, from email bodies. =3D for =, =20 for space, soft line breaks.
net
The low-level networking package: TCP, UDP, UNIX sockets, DNS resolution. net/http and net/url sit on top of this.
net/http
HTTP server and client. Batteries included — no framework required.
net/http/cookiejar
An in-memory HTTP cookie store that implements http.CookieJar. Stick it on an http.Client to persist cookies across requests.
net/http/httptest
Test helpers for HTTP handlers and servers. Fake requests, record responses, spin up local servers.
net/http/httptrace
Observe the lifecycle of an HTTP request: DNS lookup, connect, TLS handshake, first byte.
net/http/httputil
Utilities on top of net/http: reverse proxy, dump request/response, chunked encoding.
net/http/pprof
Serve runtime profiling data over HTTP at /debug/pprof/. Import for side effects to enable.
net/mail
Parse RFC 5322 addresses and message headers. Read emails, not send them (see net/smtp for that).
net/netip
A modern, comparable, immutable IP address type. Zero allocations, usable as a map key. Prefer this over net.IP in new code.
net/rpc
A Go-specific RPC framework. Frozen — not developed further. For new systems prefer gRPC or Twirp.
net/rpc/jsonrpc
JSON-RPC 1.0 codec for net/rpc. Both net/rpc and this package are frozen — use gRPC or plain HTTP+JSON for new services.
net/smtp
Simple SMTP client. Frozen — the maintainers recommend an external package for anything non-trivial.
net/textproto
Implements generic text protocols in the SMTP/HTTP/NNTP style: numbered command/response, MIME headers, pipelining.
net/url
Parse, build, and escape URLs. Handles query strings, paths, and userinfo correctly.
Errors & Logging
errors
Error inspection, wrapping, and sentinel creation. The counterpart to fmt.Errorf("%w", ...).
expvar
Expose internal counters and stats as JSON at /debug/vars. Cheap, built-in observability.
log
Classic unstructured logger. Fine for small tools; prefer log/slog for structured logs in new code.
log/slog
Structured logging (Go 1.21+). Leveled, attributable, and produces text or JSON for free.
log/syslog
Write to system log via the BSD syslog protocol. Unix-only. Frozen — new code should use log/slog + journald / your platform's logger.
Math
math
Basic math: constants, elementary functions, float classification. Operates on float64.
math/big
Arbitrary-precision integers (Int), rationals (Rat), and floats (Float). No overflow, at the cost of allocation.
math/bits
Low-level bit counting, shifting, leading/trailing zeros. Uses CPU instructions where available — very fast.
math/cmplx
Elementary functions on the complex128 type: Abs, Exp, Log, Sqrt, Phase, trig.
math/rand
Legacy pseudo-random package. Prefer math/rand/v2 in new code. Keep this around only for unchanged legacy APIs.
math/rand/v2
Pseudo-random numbers (Go 1.22+). Auto-seeded, simpler API, and not safe for cryptographic use — reach for crypto/rand for that.
Crypto
crypto
The root crypto package. Defines Hash (an enum of registered hash funcs), the Signer and Decrypter interfaces, and little else. Real work happens in subpackages.
crypto/aes
The AES block cipher. Creates a cipher.Block you combine with a mode from crypto/cipher (GCM, CBC, CTR). Never use AES-ECB.
crypto/cipher
Block-cipher modes: GCM, CBC, CTR, CFB, OFB. GCM is what you almost always want.
crypto/des
DES and triple-DES block ciphers. BROKEN for modern security. Use AES.
crypto/dsa
DSA signatures. Deprecated. Use crypto/ed25519 or crypto/ecdsa instead.
crypto/ecdh
Elliptic-curve Diffie-Hellman key exchange. The modern, misuse-resistant replacement for crypto/elliptic's low-level API.
crypto/ecdsa
ECDSA signatures (P-256 etc.). More widely interoperable than Ed25519; used in TLS, JWT ES256.
crypto/ed25519
Ed25519 signatures. Small keys, small signatures, constant-time by design. Preferred for new signing systems.
crypto/elliptic
Named NIST curves (P-224, P-256, P-384, P-521). Most new code uses crypto/ecdsa or crypto/ecdh instead — this is the lower-level curve API.
crypto/hkdf
HMAC-based Key Derivation Function. Turn a shared secret (from ECDH, say) into one or more strong keys.
crypto/hmac
Keyed Message Authentication Code. Pair with any Hash (SHA-256 usually) to authenticate messages.
crypto/md5
MD5 hashing. BROKEN for security use. Only for non-security checksums like ETags or dedup.
crypto/mlkem
ML-KEM (FIPS 203) — post-quantum key encapsulation. Produces a shared secret; combine with a classical KEM for hybrid TLS (Go 1.24+).
crypto/pbkdf2
Password-Based Key Derivation. Use a high iteration count. For new password hashing prefer Argon2 (golang.org/x/crypto).
crypto/rand
Cryptographically-secure random bytes. Reach for this for tokens, keys, nonces. NEVER math/rand for security.
crypto/rc4
RC4 stream cipher. BROKEN. Only for reading legacy protocol data you cannot avoid.
crypto/rsa
RSA signing, OAEP encryption, PSS signatures. Use 2048+ bit keys; prefer Ed25519/ECDSA for new systems.
crypto/sha1
SHA-1 hashing. BROKEN for security. Remains for Git-compatible hashing and legacy protocols.
crypto/sha256
SHA-256 and SHA-224 hashing. The exemplar for every hash package in stdlib (md5, sha1, sha512 follow the same API).
crypto/sha3
Keccak-based hashes: SHA3-256, SHA3-512, SHAKE128, SHAKE256. Different construction than SHA-2.
crypto/sha512
SHA-384 and SHA-512 hashes. Same API shape as crypto/sha256.
crypto/subtle
Constant-time operations. Use these when a timing leak would compromise secrets.
crypto/tls
TLS 1.3 and 1.2 client and server. Sits under net/http for HTTPS, but you can use it directly over any net.Conn.
crypto/x509
Parse, create, and verify X.509 certificates. The foundation of TLS and PKI.
crypto/x509/pkix
ASN.1 structures used inside X.509: Name, RDNSequence, CertificateList. Mostly used alongside crypto/x509 types.
CLI & Runtime
flag
Command-line flag parsing. Built in, zero-dependency, handles the 90% case.
os/exec
Run external commands. Connect their stdin/stdout to pipes or buffers, pass env and context, capture output.
os/signal
Receive OS signals (SIGINT, SIGTERM, etc.) via a channel or context.
os/user
Look up the current user, users by name/uid, and their groups.
Archives & Compression
archive/tar
Read and write tar archives (streaming). Typically combined with compress/gzip for .tar.gz.
archive/zip
Read and write ZIP archives. Random-access (needs io.ReaderAt for reading).
compress/bzip2
bzip2 decompression only. No writer in the standard library.
compress/flate
DEFLATE (RFC 1951). The raw compression underneath gzip, zlib, and zip. Use directly only when you know the framing.
compress/gzip
gzip (RFC 1952) reader and writer. Wraps any io.Reader/Writer.
compress/lzw
Lempel-Ziv-Welch. Used by GIF and TIFF. Rarely needed directly outside those formats.
compress/zlib
zlib (RFC 1950) reader and writer. Smaller header than gzip; common in PNG and network protocols.
Containers
container/heap
Binary heap / priority queue. Implement heap.Interface (which embeds sort.Interface) and the package drives it.
container/list
Doubly-linked list. Useful when you need to insert/remove nodes in O(1) given an element pointer — LRU caches, etc.
container/ring
Circular linked list. Fixed-size ring buffer where advancing past the end loops to the front. Rarely needed.
Testing
testing
Unit tests, benchmarks, fuzz tests, examples. Run with `go test`. File suffix _test.go.
testing/fstest
In-memory fs.FS for tests, plus TestFS to validate custom fs.FS implementations.
testing/iotest
Readers and writers that simulate slow, broken, or one-byte-at-a-time I/O. Useful for stress-testing parsers.
testing/quick
Quickcheck-style property tests. Largely superseded by native fuzzing (go test -fuzz).
testing/slogtest
Conformance tests for custom slog.Handler implementations.
testing/synctest
Test concurrent code with a fake clock and deterministic scheduling. Available since Go 1.24 (GOEXPERIMENT) / stable in 1.25+.
Templates
html
Escape and unescape HTML text. Tiny package — just EscapeString / UnescapeString.
html/template
Same syntax as text/template, but context-aware auto-escaping for HTML, JS, CSS, URL attributes. Use this for web output.
text/template
Generic text templating. Use html/template instead for anything rendered as HTML (auto-escapes).
Reflection & Unsafe
Runtime & Debug
debug/buildinfo
Read build info embedded in a Go binary on disk (module path, version, VCS revision).
debug/dwarf
Parse DWARF debugging info from binaries. Used by debug/elf, debug/macho, etc. to expose types and line tables.
debug/elf
Read ELF binaries (Linux, BSD). Inspect sections, symbols, imported libraries.
debug/gosym
Parse the Go symbol and line tables embedded in Go-built binaries. Used by profilers and crash dumpers.
debug/macho
Read Mach-O binaries (macOS, iOS). Symbols, sections, load commands.
debug/pe
Read PE binaries (Windows .exe / .dll). Sections, symbols, imports.
debug/plan9obj
Read Plan 9 a.out-format object files. Rarely needed outside Plan 9 tooling.
runtime
Hooks into the Go runtime: GOMAXPROCS, goroutine count, GC triggering, caller info, finalizers.
runtime/cgo
Support package for cgo. Most programs import this transparently via `import "C"`. Its direct API is a handle system for passing Go values to C.
runtime/coverage
Programmatically write or clear coverage counters at runtime (for long-running binaries built with -cover).
runtime/debug
GC tuning, memory limits, stack traces, and build info.
runtime/metrics
Structured, versioned access to runtime metrics (heap, GC pauses, scheduler latency, etc). Preferred over runtime.MemStats for monitoring.
runtime/pprof
Write CPU, heap, block, mutex, goroutine profiles. Analyze with `go tool pprof`.
runtime/trace
Execution tracer — fine-grained timeline of goroutines, syscalls, GC, and user-defined regions. Analyze with `go tool trace`.
Image
image
Core image types: Image interface, Rectangle, Point, and concrete types like RGBA / Gray / NRGBA.
image/color
Color models: RGBA, NRGBA, Gray, YCbCr, etc. Understand pre-multiplied vs non-premultiplied alpha.
image/color/palette
Pre-built palettes: WebSafe (216 colors) and Plan9 (256 colors). Useful for GIF encoding.
image/draw
Compose images: copy, blend, mask. The building block for simple image manipulation.
image/gif
Encode and decode GIF (including animated). Palette-based.
image/jpeg
Encode and decode JPEG. Lossy. Import _ "image/jpeg" to register it.
image/png
Encode and decode PNG. Loss-less. Import _ "image/png" to register it with image.Decode.
Database
Go Tooling
go/ast
Go syntax tree. The node types produced by go/parser and consumed by go/format, linters, and refactoring tools.
go/build
Resolve a Go package on disk given GOPATH/GOROOT, its import path, and the current build context (GOOS, GOARCH, tags).
go/build/constraint
Parse and evaluate //go:build expressions (build tags).
go/constant
Arbitrary-precision values used by go/types for untyped constants (ints, rationals, strings, booleans).
go/doc
Extract documentation from a parsed package: exported decls, doc comments, examples. Powers `go doc` and pkg.go.dev.
go/doc/comment
Parse and print the new-style (Go 1.19+) doc comment syntax — with headings, lists, links, and code blocks.
go/format
gofmt as a library. Format Go source bytes or an AST node back to canonical form.
go/importer
Provides types.Importer implementations. Used to bridge go/build / compiled packages into go/types.
go/parser
Parse Go source code into an AST. Starting point for any static analysis.
go/printer
Lower-level pretty-printer for Go AST. go/format is usually the friendlier choice.
go/scanner
Lexer for Go source. Usually you use go/parser instead — this is for tools that only need tokens.
go/token
Tokens (IDENT, INT, +, func, ...) and position info (FileSet, Pos). Thread a FileSet through every parser/format call.
go/types
Type-check Go packages. The backbone of `go vet`, staticcheck, gopls, and most analysis tooling.
go/version
Compare Go language versions like "go1.22" vs "go1.21". Handy for tools that enforce a minimum Go version.
Misc
builtin
Documentation-only package for the predeclared identifiers (len, cap, append, make, new, delete, panic, recover, any, error, ...). Always in scope.
index/suffixarray
Substring index backed by a suffix array. Fast repeated lookups into a single large corpus.
plugin
Load Go shared objects (.so) at runtime. Linux/macOS only. Fragile — all plugins must match the host's exact toolchain and deps. Rarely the right tool.
structs
Marker types you embed in your own structs to opt into special behavior. Currently just HostLayout (Go 1.23+).
syscall
Low-level, platform-specific OS primitives. Frozen — prefer os, os/exec, and golang.org/x/sys for anything new.
time/tzdata
Embed the IANA timezone database into your binary. Import for side effect when deploying to stripped-down containers without /usr/share/zoneinfo.
unique
Intern comparable values so duplicates share one allocation. Great for de-duplicating lots of repeated strings or structs (Go 1.23+).
weak
Weak pointers — references that don't prevent GC (Go 1.24+). Build caches and maps that shouldn't keep values alive.