Programming Languages
Learn Go from syntax and types to concurrency, testing, tooling and building real services.
A complete path for becoming a productive Go developer. It covers the language itself, modules and packages, goroutines and channels, error handling, testing, the standard library, building CLIs and web services, and the toolchain for linting, profiling and deployment. Each subject links the official Go documentation or the library's own docs.
The subjects follow the roadmap.sh Go roadmap.
Go is a statically typed, compiled language from Google built for simple syntax, fast builds and first-class concurrency. It produces single static binaries, ships a formatter, test runner and module system in one toolchain, and powers much of the cloud-native world (Docker, Kubernetes, Terraform).
Readable code that new team members pick up quickly, compile times measured in seconds, goroutines for cheap concurrency and a strong standard library for networking. The trade-off is a deliberately small feature set.
Designed in 2007 by Robert Griesemer, Rob Pike and Ken Thompson out of frustration with slow C++ builds; open-sourced in 2009, Go 1.0 and its compatibility promise arrived in 2012 and generics in 1.18.
Install the official toolchain, check go version, and use go env to inspect GOPATH, GOROOT and GOPROXY. With modules you can keep projects anywhere; pair with the gopls language server in your editor.
A package main with a func main() that calls fmt.Println. Create a module with go mod init, then go run . to compile and run in one step.
The single entry point for the toolchain: building, running, testing, formatting, vetting, fetching modules and reading docs. go help <topic> documents every subcommand and concept offline.
Go declares names with var, := and const, and every variable always holds a valid value from the moment it exists. Unused local variables and imports are compile errors, which keeps code tidy but surprises newcomers.
var x T works at package and function level and lets you omit the initialiser; x := v only works inside functions and infers the type. := must declare at least one new name on its left.
Uninitialised variables get 0, false, "" or nil depending on type. Good Go types are designed so their zero value is useful, like sync.Mutex or bytes.Buffer.
Constants are compile-time values and can be untyped, giving them arbitrary precision until used. Inside a const ( ... ) block, iota counts 0, 1, 2… and is the idiomatic way to build enums and bit flags.
Scope is lexical, by block. Re-declaring a name with := in an inner block (often err inside an if) creates a new variable that hides the outer one; go vet -vettool shadow checkers catch this.
Go has booleans, sized integer and float types, complex numbers, strings and runes as its basic types, and no implicit conversion between any of them. Mixing int and int64 in one expression is a compile error until you convert explicitly.
bool holds true or false and does not convert to or from integers. && and || short-circuit.
int8 to int64, uint8 to uint64, plus platform-sized int/uint and uintptr. Overflow wraps silently; use int by default and math/bits or checks when overflow matters.
float32 and float64 follow IEEE 754; untyped float constants default to float64. Never compare money with floats, and remember NaN != NaN.
complex64 and complex128 are built in, created with complex(re, im) or literals like 3+4i, and taken apart with real and imag. math/cmplx holds the functions.
rune is an alias for int32 holding one Unicode code point; a rune literal is written in single quotes like 'é'. Ranging over a string yields runes, while indexing yields bytes.
Written T(v), always explicit. Numeric conversions can truncate; string(65) gives "A", not "65" — use strconv.Itoa and strconv.Atoi for number–text conversion.
Daily Go work runs through a handful of go subcommands and the documentation that is generated straight from source comments. Learn the core commands early; everything else in the toolchain builds on them.
Compiles a package to a temporary binary and runs it. Handy during development; go run . runs the main package in the current directory.
Compiles packages and writes an executable for main packages. -o sets the output path, -race enables the race detector and -ldflags passes linker flags.
Builds and places the binary in $GOBIN (default $GOPATH/bin). go install example.com/tool@latest installs a tool without touching the current module.
Runs gofmt over packages so all Go code shares one layout. Most editors format on save; there is nothing to configure and nothing to argue about.
Maintains go.mod and go.sum: init, tidy, download, vendor, why and graph. go get is what adds or upgrades a dependency.
Builds and runs _test.go files. Key flags: -run to filter, -v, -race, -cover, -bench, and -count=1 to bypass the test cache.
Removes build artefacts; -cache, -testcache and -modcache clear the build cache, cached test results and downloaded modules when something seems stale.
Prints documentation for a package or symbol in the terminal, e.g. go doc strings.Cut or go doc -all net/http. pkg.go.dev renders the same comments for published modules.
Shows the toolchain version; go version -m ./binary lists the module versions compiled into a binary, useful when auditing what shipped.
An array has a fixed length that is part of its type, so [3]int and [4]int are different types. Arrays are values: assigning or passing one copies every element, which is why most code uses slices instead.
A slice is a small header — pointer, length, capacity — over a backing array. Slicing shares memory, so writes through one slice can show up in another; append, copy and the slices package are the everyday tools.
cap(s) is how far the slice can grow before append must allocate a new array and copy. After a reallocation the new slice no longer aliases the old one — always use the result of append.
make([]T, len, cap) allocates slices (and maps and channels). Preallocating capacity when you know the size avoids repeated growth.
Since Go 1.20 [4]byte(s) copies a slice into an array; it panics if the slice is shorter. Converting to an array pointer, (*[4]byte)(s), shares memory instead.
Slicing an array, a[:], gives a slice backed by that same array — no copy, so changes are visible through both.
A string is an immutable sequence of bytes, conventionally UTF-8. len counts bytes, not characters; use strings.Builder to build strings in loops and the strings, unicode/utf8 and strconv packages for the rest.
Backquoted strings: no escapes are processed and they may span lines. Ideal for regular expressions, SQL, JSON fixtures and struct tags.
Double-quoted strings that process escapes like \n, \t, \u00e9 and \xff. They cannot contain a raw newline.
Built-in hash tables, map[K]V, created with make or a literal. Reads from a nil map return zero values but writes panic, iteration order is deliberately random, and maps are not safe for concurrent writes.
v, ok := m[k] tells a missing key apart from a stored zero value. The same two-value form appears with type assertions and channel receives.
Structs group named fields into a type and are Go's main way to model data. Fields starting with a capital letter are exported; structs are values, so pass a pointer when you need to mutate or avoid copying a large one.
Backquoted metadata after a field, read through reflection, such as json:"name,omitempty". encoding/json only sees exported fields, and a typo in a tag fails silently — go vet checks the syntax.
Listing a type without a field name promotes its fields and methods to the outer struct. It is composition, not inheritance: the embedded value still receives the method call.
Go has if and switch with no parentheses around conditions and mandatory braces. Both accept a short init statement, which keeps temporary variables like err scoped to the branch.
if v, err := f(); err != nil { ... } is the signature Go shape. Conditions must be bool; there is no truthiness.
Chains of else if work as expected, but idiomatic Go prefers returning early from the error branch so the happy path stays unindented.
Cases do not fall through unless you write fallthrough, can list several values, and a tagless switch { case x > 0: ... } replaces long if-else chains.
for is Go's only loop keyword, covering C-style, while-style and infinite loops plus range. Since Go 1.22 each iteration gets its own loop variable, fixing the classic closure-capture bug.
for i := 0; i < n; i++, for cond { } as a while loop, and bare for { } for an infinite loop exited with break or return.
Iterates slices, arrays, strings, maps, channels, integers (for i := range 10) and, since Go 1.23, iterator functions. The value is a copy of the element.
Order is randomised on every run. For deterministic output collect the keys, sort them with slices.Sorted(maps.Keys(m)), then loop.
range over a string decodes UTF-8 and yields the byte offset and the rune; invalid bytes become U+FFFD. A plain index loop walks bytes instead.
Leaves the innermost for, switch or select. Inside a switch within a loop it only exits the switch — use a labelled break Outer to leave the loop.
Skips to the next iteration of the innermost loop, or a labelled outer loop with continue Outer.
Jumps to a label in the same function and cannot skip over variable declarations. It exists for generated code and rare cleanup paths; normal code uses loops and early returns.
Functions are first-class values with typed parameters and possibly several results. Go has no default arguments or overloading; defer schedules cleanup that runs when the function returns.
Declared with func name(a, b int) int. Consecutive parameters of one type share the type name, and a function only exported outside its package if its name is capitalised.
A final parameter ...T arrives as a []T. Pass an existing slice with f(s...); note the function then shares that slice's backing array.
Functions return several values, most often (result, error). Discard one with _; you must handle or ignore each explicitly.
Function literals written inline, used for callbacks, defer func() { ... }() and launching goroutines.
A function literal that captures variables from its surrounding scope by reference, keeping them alive as long as the closure lives — useful for generators, middleware and counters.
Result parameters can be named, start at their zero value and are returned by a bare return. Most useful when a deferred function needs to modify the returned error.
Every argument is copied. Slices, maps, channels and pointers copy a small header or address, so callees can still mutate what they point at — but reassigning the parameter itself never affects the caller.
*T holds the address of a T; &x takes an address and *p dereferences. There is no pointer arithmetic, and returning a pointer to a local variable is safe because the compiler moves it to the heap when needed.
The zero value is nil and dereferencing it panics. new(T) allocates a zeroed T and returns *T; &T{...} does the same with a literal.
Fields are accessed through a pointer with the same dot syntax, p.Name. Pass *Struct to mutate it or to avoid copying large values.
Maps and slices already refer to shared data, so pointers to them are rarely needed. The exception: a function that appends and must change the caller's slice length should return the new slice.
Go decides stack versus heap per value; you never free memory by hand. Fewer heap allocations means less GC work, which go test -benchmem makes visible.
A concurrent, non-moving mark-and-sweep collector with short pauses. GOGC trades memory for CPU and GOMEMLIMIT sets a soft memory cap, important in containers.
A method is a function with a receiver, declared as func (t T) Name(), and can only be defined on types in the same package. Methods are what let a type satisfy an interface; plain functions are fine for everything else.
func (t *T) M() lets the method modify the receiver and avoids copying it. Use them when any method needs to mutate, or the type holds a mutex; keep receivers consistent across a type. Only *T then satisfies interfaces needing M.
func (t T) M() works on a copy, so changes do not escape the method. A good fit for small, immutable types such as time.Time; both T and *T have value-receiver methods in their method sets.
An interface is a set of method signatures, satisfied implicitly by any type with those methods — no implements keyword. Keep them small, define them where they are used, and accept interfaces but return concrete types.
An interface value holds a dynamic type and value. Gotcha: an interface holding a nil *T is not itself nil, which trips up err != nil checks.
interface{}, spelled any since Go 1.18, accepts every value. You lose static typing, so get the value back out with assertions or prefer generics.
Interfaces compose by listing others, e.g. io.ReadWriter embeds io.Reader and io.Writer. Build big contracts from small ones.
v := x.(T) extracts the concrete value and panics on mismatch; v, ok := x.(T) reports failure instead. Also works for asserting to another interface.
switch v := x.(type) { case int: ... case string: ... } branches on the dynamic type, with v typed per case.
Type parameters, added in Go 1.18, let functions and types work over many types with compile-time checking. Use them for containers and algorithms; reach for interfaces when behaviour, not type, varies.
Before 1.18 you copied code per type or used interface{} and runtime assertions. Generics remove that duplication without giving up type safety.
func Map[T, U any](s []T, f func(T) U) []U — type parameters in square brackets before the regular ones. slices and maps in the standard library are good models.
Types can take parameters too, like type Stack[T any] struct { items []T }. Methods cannot add their own type parameters beyond the type's.
Constraints are interfaces that may list types: any, comparable, cmp.Ordered, or your own ~int | ~float64. The ~ admits types whose underlying type matches.
The compiler usually infers type arguments from the call's arguments, so you write Max(a, b) instead of Max[int](a, b). Explicit arguments are needed when nothing to infer from exists.
Errors are ordinary values returned as the last result and checked with if err != nil. Add context as errors travel up, inspect them with errors.Is and errors.As, and reserve panic for genuinely unrecoverable bugs.
A built-in interface with one method, Error() string. Any type implementing it is an error, so custom types can carry codes or fields that callers pull out with errors.As.
Creates a simple error from a fixed message. Each call yields a distinct value, so compare against a stored package-level variable, not a fresh errors.New.
Builds a formatted error message; with the %w verb it also wraps the underlying error so errors.Is and errors.As can still find it.
Wrapping adds context while keeping the original reachable. errors.Unwrap, errors.Is, errors.As walk the chain, and errors.Join combines several errors.
Exported error variables such as io.EOF or sql.ErrNoRows that callers test with errors.Is. They become part of your API, so add them sparingly.
panic unwinds the stack running deferred calls; recover inside a deferred function stops it. Servers use this at request boundaries — never as a replacement for returning errors.
An unrecovered panic prints every goroutine's stack; GOTRACEBACK controls the detail and runtime/debug.Stack captures one in code. Delve (dlv) is the standard debugger.
A module is a versioned tree of packages described by go.mod, with go.sum pinning checksums. Go uses minimal version selection, so builds are reproducible without a lock file, and modules are fetched through GOPROXY.
Creates go.mod with a module path, usually the repository URL such as github.com/you/app. The path becomes the prefix of every import in the module.
Adds missing requirements and removes unused ones so go.mod and go.sum match the imports. Run it before committing; CI often fails if it would change anything.
Copies dependencies into vendor/; builds then use it automatically. Useful for air-gapped or audited builds, at the cost of a large directory in the repo.
Every Go file belongs to a package, one per directory. Capitalised identifiers are exported, internal/ directories restrict who may import, and init() functions run once at program start.
Imports use full module paths, unused imports are errors and import cycles are forbidden. You can alias (import j "encoding/json"), import for side effects with _, and only packages under the same parent may import an internal package.
Add one with go get example.com/pkg@v1.2.3 (or just import it and run go mod tidy). Check pkg.go.dev for docs, licence and importers, and remember a new major version (v2+) has /v2 in its import path.
Push the module to a public repository and tag a semantic version like v1.0.0; the module proxy picks it up on first request. Breaking changes need a new major version path, and retract in go.mod withdraws bad releases.
Lightweight threads started with go f(), multiplexed by the runtime onto OS threads with small growable stacks — running thousands is normal. Every goroutine needs a clear way to finish, or it leaks.
Typed conduits for passing values between goroutines, made with make(chan T). Only the sender should close a channel; receiving from a closed channel yields zero values, sending to one panics, and nil channels block forever.
An unbuffered send waits for a receiver, synchronising both sides. make(chan T, n) lets n sends proceed without a receiver — useful for smoothing bursts, but it hides backpressure problems.
Waits on several channel operations and runs whichever is ready first, choosing randomly among ties. A default case makes it non-blocking; pairing with ctx.Done() or time.After adds cancellation and timeouts.
A fixed number of goroutines reading jobs from one channel and writing results to another, bounding concurrency against a database or API. errgroup.Group with SetLimit is a compact alternative that also propagates errors.
Low-level primitives for shared memory: Mutex, RWMutex, WaitGroup, Once, Pool, Map and Cond, plus sync/atomic. None of these may be copied after first use — go vet reports it.
mu.Lock() then defer mu.Unlock() guards shared state. RWMutex allows many readers or one writer; keep critical sections short and never hold a lock while blocking on a channel.
Waits for a set of goroutines: Add before starting each, Done when it ends, Wait to block. Go 1.25 added wg.Go(f) which does the counting for you.
A context.Context carries cancellation, deadlines and request-scoped values across API boundaries and goroutines. Pass it as the first parameter named ctx, never store it in a struct, and always call the cancel function you are given.
context.WithTimeout, WithDeadline and WithCancel derive child contexts; when the parent is cancelled every child is too. Long-running work should check ctx.Done() or ctx.Err().
Stopping database queries and outbound HTTP calls when a client disconnects (r.Context()), graceful shutdown with signal.NotifyContext, and carrying trace IDs. Avoid stuffing optional parameters into WithValue.
Reusable shapes built from goroutines and channels: pipelines, fan-out/fan-in, worker pools, rate limiting and bounded parallelism. Each must define who closes which channel and how cancellation stops every stage.
Merging several input channels into one, typically with a goroutine per input and a WaitGroup that closes the output when all inputs are drained.
Several goroutines reading from the same channel to spread CPU- or IO-heavy work. Results arrive out of order unless you carry an index.
A chain of stages, each a goroutine that receives from an inbound channel, transforms, and sends on an outbound one. A done channel or context lets downstream stages abort upstream work.
A data race is two goroutines touching the same memory without synchronisation, at least one writing; the result is undefined behaviour. Go ships a dynamic detector that finds races in the code paths your tests and runs actually execute.
Tests live in _test.go files as func TestXxx(t *testing.T) and run with go test. Use t.Errorf to keep going, t.Fatalf to stop, t.Run for subtests and t.Helper in helpers; no assertion library is required.
A slice of anonymous structs listing inputs and expected outputs, looped over with t.Run(tc.name, ...). Adding a case is one line and each case reports independently.
Depend on small interfaces so tests can pass hand-written fakes. Generators like mockgen exist, but a simple stub struct is usually clearer.
httptest.NewRecorder exercises a handler in-process; httptest.NewServer starts a real local server to test clients against.
func BenchmarkXxx(b *testing.B) run with go test -bench=. -benchmem. Go 1.24 added b.Loop(); compare runs statistically with benchstat.
go test -coverprofile=c.out then go tool cover -html=c.out shows which lines ran. Since Go 1.20 whole binaries can be built with -cover for integration coverage.
Go's standard library is broad enough to build production servers, CLIs and tooling without third-party code. Lean on it first; most popular libraries wrap or follow its interfaces like io.Reader and http.Handler.
io.Reader and io.Writer connect everything: files, network connections, buffers and compressors. os.ReadFile and os.WriteFile cover small files; stream big ones with io.Copy.
Parses command-line flags: flag.String, flag.Int, flag.Parse(). Good for simple tools; switch to a CLI library when you need subcommands.
time.Time, time.Duration, timers and tickers. Layouts use the reference date Mon Jan 2 15:04:05 MST 2006; measure elapsed time with time.Since, which uses the monotonic clock.
json.Marshal/Unmarshal for whole values and json.NewDecoder/Encoder for streams. Unknown fields are ignored unless you call DisallowUnknownFields.
Files, directories, environment variables (os.Getenv, os.LookupEnv), process args and exit codes. os.Exit skips deferred calls.
Buffered readers and writers plus bufio.Scanner for line-by-line input. Scanner's default 64 KB token limit fails on long lines — raise it with Buffer. Remember to Flush writers.
log/slog (Go 1.21) gives structured, levelled logging with text and JSON handlers. Attach common fields with logger.With and pass context-aware calls like InfoContext.
RE2 syntax with guaranteed linear-time matching, so no backreferences or lookarounds. Compile once at package level with regexp.MustCompile.
The //go:embed directive bakes files into the binary as a string, []byte or embed.FS — templates, migrations and static assets ship as one executable.
Go is a favourite for command-line tools because it cross-compiles to a single dependency-free binary that starts instantly. Start with flag and os.Args; adopt a library for subcommands, help text and completions.
The library behind kubectl, gh and Hugo: nested commands, POSIX flags via pflag, generated help and shell completion. Often paired with Viper for config.
A lighter declarative alternative to Cobra: define commands and flags as struct literals, with env-var fallbacks built in.
Charm's framework for interactive terminal UIs using the Elm architecture (model, update, view). Pair with Bubbles components and Lip Gloss styling.
Go's net/http is production-grade on its own, and since Go 1.22 its router matches methods and path parameters. Frameworks add conveniences like binding and middleware chains, but many teams ship with the standard library plus a few helpers.
http.ServeMux with patterns like GET /items/{id} and r.PathValue("id"), http.Handler middleware, and an http.Server with explicit timeouts — the zero-value defaults have none.
Define services in .proto files, generate Go code with protoc-gen-go and protoc-gen-go-grpc, and get typed, streaming RPC over HTTP/2 between services.
The most widely used Go web framework: fast radix-tree routing, request binding and validation, and middleware. Handlers take *gin.Context instead of the standard signature.
A minimalist framework with grouped routes, data binding and a rich middleware set; handlers return an error, which centralises error handling.
An Express-style API on top of fasthttp rather than net/http. Very fast, but incompatible with standard handlers and middleware.
A full-stack MVC framework with its own ORM, config, caching and code generator — closer to Rails or Django than the rest of the ecosystem.
database/sql provides a driver-agnostic connection pool, prepared statements and transactions. Always pass a context, close rows, check rows.Err(), and tune SetMaxOpenConns for your database.
The go-to PostgreSQL driver: usable through database/sql or its own faster native interface with pgxpool, COPY, LISTEN/NOTIFY and rich type support.
A full ORM with associations, hooks, migrations and soft deletes. Productive for CRUD; watch generated SQL and N+1 queries, and know that zero values are skipped in struct-based updates.
Production services log structured key-value records, usually JSON, so they can be searched and aggregated. The standard log/slog covers most needs; dedicated libraries focus on near-zero allocations.
Push updates to clients over WebSockets or Server-Sent Events. SSE needs only net/http and a flushing writer; WebSockets need a library, and scaling either across instances needs a broker such as Redis or NATS.
A small framework over a WebSocket library that manages sessions and broadcasting, so a chat-style hub takes a few lines.
A standalone, Go-written real-time server: your backend publishes to channels over an API and Centrifugo fans messages out to connected clients via WebSocket, SSE and more.
Static analysis catches bugs the compiler allows: suspicious printf verbs, copied locks, unchecked errors and known-vulnerable dependencies. Run these in CI alongside go test -race.
Ships with the toolchain and reports likely mistakes such as wrong Printf arguments, unreachable code, copied mutexes and bad struct tags. go test runs a subset automatically.
Does everything gofmt does and also adds missing and removes unused imports, grouping standard-library imports first. gopls runs it on save.
A fast, configurable successor to the retired golint, checking style and naming rules you can enable, disable or tune per project.
A deep analyser that finds bugs, dead code, deprecated API use and simplifications that go vet misses. Also bundled inside golangci-lint.
A runner that executes dozens of linters in parallel with shared caching and one .golangci.yml config. The usual choice for CI.
Checks your module against the Go vulnerability database and, unlike plain dependency scanners, only reports vulnerabilities whose affected functions your code actually calls.
Go favours generating code over runtime magic: mocks, enums' String methods, protobuf stubs and SQL bindings are generated and committed. Build tags choose which files compile for a platform or feature.
Scans for //go:generate command args comments and runs them. It never runs during go build; run it yourself and commit the output. stringer is the classic example.
A //go:build linux && !cgo line at the top of a file includes it only when the expression holds; pass custom tags with go build -tags=integration.
Measure before optimising: benchmarks show cost, profiles show where it goes, and execution traces show scheduling and latency. All of it is built into the toolchain.
CPU, heap, goroutine, mutex and block profiles, collected from tests (-cpuprofile) or a live server via net/http/pprof, and explored with go tool pprof -http=:8080.
The execution tracer records goroutine scheduling, GC, syscalls and blocking over time; view it with go tool trace. Ideal for latency and concurrency problems a profile averages away.
Add -race to go test, go run or go build. It reports the conflicting accesses with stacks, costs several times the CPU and memory, and needs cgo on most platforms.
Go deploys as one static binary, so containers can be as small as scratch or distroless images. Embed version info at build time and ship a binary per target platform.
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" gives a small, reproducible, fully static binary. Version and VCS info are embedded automatically and readable with go version -m.
Set GOOS and GOARCH (e.g. GOOS=linux GOARCH=arm64) and build — no extra toolchain needed unless cgo is involved. go tool dist list prints every supported pair.
Runtime internals and escape hatches: how allocation really works, reflection, unsafe, cgo and linker tricks. Useful for performance work and libraries; most application code never needs them.
Size-classed allocation with per-P caches, the GC pacer, GOMEMLIMIT and sync.Pool for reuse. runtime.MemStats and GODEBUG=gctrace=1 show what the collector is doing.
The compiler decides whether a value can live on the stack; go build -gcflags=-m prints why something escapes. Returning pointers and storing in interfaces are common causes.
reflect.TypeOf and reflect.ValueOf inspect and modify values at runtime — the machinery behind encoding/json and ORMs. Slow and panic-prone, so keep it inside libraries.
unsafe.Pointer, Sizeof, Offsetof, unsafe.String and unsafe.Slice bypass the type system for zero-copy tricks. Breaks portability and the compatibility promise if misused.
Beyond //go:build lines, file-name suffixes like _windows.go or _arm64_test.go act as implicit constraints. Combine them to maintain platform-specific implementations behind one API.
import "C" with a preamble lets Go call C. It costs per-call overhead, complicates cross-compiling and static builds, and pointer-passing rules are strict.
-gcflags reaches the compiler (-m, -N -l to disable optimisation for debugging); -ldflags reaches the linker (-X main.version=1.2.3, -s -w to strip symbols).
The plugin package loads -buildmode=plugin shared objects on Linux and macOS, but host and plugin must be built with identical toolchains and deps. Most projects use RPC-based plugins instead.