138 terms across 10 categories
An adapter is a type that exposes the interface you need by wrapping a type you already have. In Go that is a struct with an embedded or named field and methods that forward, translate, or both.
A decorator wraps a value of an interface and implements the same interface, adding behaviour before or after forwarding. Logging, retries, and metrics around a Store or http.RoundTripper are decorators.
Fan-out starts several goroutines from one channel of work. Fan-in merges several channels into one. Together they are how Go pipelines parallelize a stage and then collect results.
Functional options are func(*Config) values passed to a constructor: NewServer(WithAddr(":8080"), WithTimeout(time.Second)). They keep the call readable when many settings are optional.
Middleware is a function that wraps another function, usually an http.Handler, to run code before and after the inner call. Logging, auth, and request IDs are middleware. The same wrapping idea applies to any func(T) error.
A pipeline is a sequence of stages connected by channels. Each stage is a goroutine (or a pool) that receives values, transforms them, and sends them on. Closing the first channel should unwind the rest.
A repository is an interface that loads and stores domain values, hiding SQL (or another store). Handlers depend on the interface. Tests substitute a fake. The concrete type talks to database/sql.
A singleton is a value of which there is one in the process. In Go that is usually a package-level variable initialized with sync.Once or init, not a class with a private constructor.
A worker pool is a fixed number of goroutines that pull jobs from a channel (or from errgroup with a limit). It caps concurrency so you do not start one goroutine per item when the item count is unbounded.
type Count int defines a new named type with int as its underlying type. type Count = int is an alias: Count and int are the same type. Definitions need conversions; aliases do not.
Build tags are comments that include or exclude a file from a build based on OS, architecture, Go version, or a custom name you pass with -tags. They are how one package ships Windows and Linux files without #ifdef.
A closure is a function literal that refers to variables from the enclosing function. Those variables stay alive as long as the closure does, and assignments inside the closure change the original variables.
if, else if, and else pick one branch of code to run based on a boolean test. Go drops the parentheses, requires the braces, and lets you declare variables in the if itself.
A custom error type is any type you define that has an Error() string method. You reach for one when the caller needs structured facts about the failure, not a sentence.
defer schedules a function call to run when the surrounding function exits, no matter how it exits. It is Go's tool for cleanup: unlock this mutex, close this file, stop this timer.
error is an interface with one method, Error() string. Functions return it as a last result. A nil error means success; a non-nil error means the caller must handle or wrap the failure.
fmt.Errorf("load config: %w", err) builds a new error whose message includes context and whose cause is err. errors.Is and errors.As walk that chain. %w is the verb that preserves the cause.
A function is a named block of code with a typed parameter list and a typed result list. Functions are values: you can assign them, pass them, and return them.
Generics let you write a function or type once, with type parameters, and use it with many concrete types. Constraints say which operations those types must support.
go generate scans source files for //go:generate comments and runs the commands written there. It is a convention for code generation, not a build step the compiler runs on its own.
A module is a versioned tree of Go packages identified by a module path, usually a repository URL. It is the unit you tag, download, and import; a package is one folder inside it.
go.mod is the file at the root of a module that names the module, pins the Go language version, and lists the other modules this code depends on. The toolchain reads it on every build.
gofmt is the standard formatter for Go source. It decides indentation, spacing, and import grouping. The compiler does not run it, but every Go project expects its output.
iota is a predeclared identifier that counts from 0 in a const block, incrementing on each new line. It is how Go writes related constants and bit flags without a separate enum type.
Go has one loop keyword, for. It covers C-style three-clause loops, while-style conditions, infinite loops, and range over strings, arrays, slices, maps, and channels.
main is the function the runtime calls to start an executable. init is a package-level function that runs automatically before main, once per package, in import order.
new(T) allocates a zero T and returns *T. make creates a usable slice, map, or channel and returns that type, not a pointer. You almost never need new; you need make whenever you will write to a map or grow a slice with a known size.
A Go function can return several values in one call. The usual pair is (result, error). The caller receives them as a list of assignments, not as a tuple object.
Named returns declare result variables in the function signature. A bare return yields those variables. Deferred closures can assign to them after the return statement has started.
Operators combine or compare values: arithmetic, comparison, logical, bitwise, assignment, and address. Go keeps a small set, requires matching types, and has no ternary and no implicit truthiness.
A package is a folder of Go source files that compile together and share unexported names. Every .go file in that folder declares the same package name, and other code imports the folder path, not the file.
panic stops the current goroutine and runs deferred calls as the stack unwinds. recover, called from a deferred function, catches that panic and resumes normal execution in the deferred function's caller.
A pointer holds the address of a value. T is "pointer to T." &x takes the address of x. p reads or writes the value p points at. The zero pointer is nil.
Go's primitive types are the built-in scalars: booleans, integers, floating-point numbers, complex numbers, and strings. They are values, they copy on assignment, and they have no methods until you declare a named type on top of them.
range walks a string, array, slice, map, or channel (and, since Go 1.22, integer counts). Each iteration yields an index or key and a copy of the element, or a received value.
:= declares one or more variables and assigns them in a single statement, inferring each type from the right-hand side. It is legal only inside functions.
switch picks one branch out of many by comparing a value against a list of cases. Go's version never falls through by accident, accepts several values per case, and can drop the value entirely to become a tidy if-else chain.
A type parameter is a name in brackets on a function or type, such as T in func FirstT anyT) (T, bool). Call sites substitute a real type, often inferred from the arguments.
A type set is the collection of types that satisfy a constraint. Interfaces used as constraints can list types with | and can embed other constraints, which is how int | int64 means "these integers or any named type whose underlying type is one of them."
A type switch looks at the dynamic type stored in an interface value and runs the matching case. You write switch v := x.(type) instead of a chain of type assertions.
A constant is a compile-time value declared with const. Untyped constants keep their kind (integer, float, rune, string, bool) and adapt to the type you assign them into. Typed constants are locked to one type.
A variable is a named storage location with a fixed type. You declare it with var, or with := when the compiler can infer the type from the value on the right.
A variadic parameter is a final parameter written args ...T. The function receives a []T, and callers may pass zero or more T values, or a slice unpacked with ....
A workspace is a go.work file that tells the toolchain to use several local modules together as if they were already required at the versions on disk. It is a development overlay, not something you publish.
The zero value is what a variable holds when you declare it and do not assign anything. Every type has one: 0, false, "", nil, or a struct whose fields are themselves zero.
any is a predeclared alias for interface{}. It means "a value of some type" in ordinary code, and "no constraint" on a type parameter. It does not add methods or runtime checks.
Embedding places a type inside a struct (or interface) without a field name. The outer type gains the inner type's fields and methods by promotion. It is composition, not subclassing.
The empty interface interface{} has no methods, so every type satisfies it. It is the type of a value whose concrete type is decided at runtime. any is an alias for the same type.
A struct field whose name starts with an uppercase letter is exported: other packages can read and write it. A lowercase field is visible only inside the struct's package.
A type implements an interface by having the required methods. You never write implements. The compiler checks the method set at every assignment to an interface variable.
A type satisfies an interface when its method set contains every method of the interface, with matching names and signatures. Satisfaction is checked at compile time on assignment, not at the type's declaration.
An interface is a named set of methods. A type satisfies it by having those methods — no implements line. Values of the interface hold a dynamic type and a value of that type.
A method is a function with a receiver argument written before the name: func (s Session) Expired() bool. The receiver type is any named type in the same package, not only a struct.
A value receiver (func (s Session)) gets a copy of the struct. A pointer receiver (func (s *Session)) gets the address, so the method can mutate the original and avoid copying a large value.
Promotion is the rule that lets you use an embedded type's fields and methods as if they were declared on the outer type. s.Lock() works when s embeds sync.Mutex, because Lock is promoted.
A struct is a named group of fields that you handle as a single value. Go has no classes, so structs are how you model "a thing with data" — and methods are attached to them separately.
A type assertion x.(T) says that the value in interface x has dynamic type T (or a type that satisfies interface T). The comma-ok form returns a bool instead of panicking when it does not.
append adds elements to a slice and returns a slice that may use the same array or a newly allocated one. Always assign the result: s = append(s, v).
An array is a numbered sequence of elements whose length is part of the type. [3]int and [4]int are different types. Assignment copies every element.
container/heap is a standard-library package that maintains a slice as a binary heap. You implement heap.Interface (Len, Less, Swap, Push, Pop) and call heap.Init, heap.Push, and heap.Pop.
container/list is a doubly linked list. Elements are *list.Element nodes. Use it when you must insert or remove from the middle in constant time and you already hold the node. Prefer a slice for almost everything else.
copy(dst, src) copies elements from src into dst and returns how many it copied: the minimum of the two lengths. It does not grow dst. Overlapping slices are safe.
v, ok := m[k] returns the value and a bool that is true only when k is in the map. Use it when the zero value of V is also a legitimate stored value.
A map is an unordered hash table from keys to values: map[K]V. Keys must be comparable. The zero map is nil and is safe to read, not to write.
A byte is an 8-bit value (uint8). A rune is a Unicode code point (int32). Strings and []byte are sequences of bytes. Decoding UTF-8 produces runes, which may take one to four bytes each.
Capacity is how many elements the backing array can hold from the start of the slice without allocating a new array. len is how many are in use. append reallocates when len would exceed cap.
A slice is a view of an array: a pointer, a length, and a capacity. Most Go sequences are slices. They grow with append, they share storage when you reslice, and the zero slice is nil.
A string is an immutable sequence of bytes, usually UTF-8 text. Assignment copies a header (pointer and length). Indexing yields a byte. Ranging yields runes.
A struct used as a record is a fixed, named bundle of fields you pass as one value: a row, a coordinate, a key. It is data, not an object hierarchy. Use it when a map of string keys would lose types and names.
sync.Map is a map that is safe for concurrent use without an extra mutex. Keys and values are any. It is specialized for a few access patterns; it is not a drop-in faster map.
The sync/atomic package provides atomic load, store, add, and compare-and-swap on integers and pointers. A single atomic operation is indivisible: another goroutine sees the old value or the new one, not a torn write.
A buffered channel holds a fixed number of values: make(chan T, n). Send parks only when the buffer is full. Receive parks only when the buffer is empty.
A channel type can be restricted to send-only (chan<- T) or receive-only (<-chan T). The restriction is checked at compile time and documents which side of the pipe a function owns.
A channel is a typed pipe between goroutines: chan T. Send ch <- v and receive v := <-ch synchronize the two sides. Channels move values and, when unbuffered, also act as a handshake.
context.Context carries a deadline, a cancellation signal, and optional request-scoped values across API boundaries. The first argument of an outgoing call is, by convention, ctx.
Cancelling a context closes its Done channel and makes Err return context.Canceled (or DeadlineExceeded if a deadline fired). Child contexts see the same signal. The cancel function returned by WithCancel or WithTimeout releases resources.
A data race is two goroutines accessing the same memory at the same time, without synchronization, where at least one access is a write. In Go that is a bug; the race detector exists to find it.
A deadlock is a set of goroutines that will never proceed because each is waiting for another. The runtime detects when every goroutine is asleep and crashes with fatal error: all goroutines are asleep - deadlock!.
golang.org/x/sync/errgroup runs a set of goroutines and returns the first error. Group.Go starts a function; Wait joins. WithContext cancels the others when one fails.
A goroutine is a function executing concurrently, started with go f(). The runtime multiplexes many goroutines onto OS threads. They are cheaper than threads, but they still need a way to stop and to share data safely.
The race detector is a compiler and runtime instrument you enable with go test -race or go build -race. It reports concurrent unsynchronized access to the same memory when at least one access is a write.
select waits until one of several channel operations can proceed, then runs that case. If several are ready, it picks one at random. It is the switch of concurrent Go.
A default case in select runs when none of the channel operations can proceed right now. That makes the select non-blocking: try the channels, otherwise continue.
sync.Cond is a condition variable: goroutines Wait until another goroutine Signals or Broadcasts. It must be used with a Locker, usually a *sync.Mutex, and a condition you check in a loop.
sync.Mutex is a mutual-exclusion lock. Lock waits until the mutex is free, then takes it. Unlock releases it. Only one goroutine holds the lock at a time.
sync.Once runs a function at most once, even if many goroutines call Do at the same time. Later Do calls wait for the first run to finish, then return without running the function again.
sync.Pool is a concurrent free-list of temporary objects. Get returns a stored value or calls New. Put returns a value for later Get. The garbage collector may discard pooled items at any time.
sync.RWMutex is a reader-writer lock. Many goroutines may hold RLock at once. Lock is exclusive. Use it when reads are common and writes are rare.
sync.WaitGroup waits until a counter reaches zero. Add raises the counter, Done lowers it, Wait blocks until the count is zero. It is the usual way to join a set of goroutines.
An unbuffered channel has capacity 0: make(chan T). A send completes only when another goroutine is ready to receive. That rendezvous is both data transfer and a synchronization point.
A benchmark is func BenchmarkXxx(b *testing.B) in a _test.go file. go test -bench runs the function in a loop b.N times and reports ns/op, and optionally allocs/op.
A fuzz test is func FuzzXxx(f *testing.F) that registers seed inputs and a f.Fuzz callback. The toolchain mutates the seeds and looks for panics, failures, and go test crashes.
go test compiles test files and runs them. Flags select packages, names, race detection, fuzzing, benchmarks, cache, and verbosity. CI should pin the flags that define "green."
The net/http/httptest package tests HTTP handlers without a listening socket you manage. httptest.NewRecorder captures a response. httptest.NewServer starts a local server for client tests.
In Go you mock by defining a small interface and passing a fake implementation in tests. Implicit satisfaction means the production type does not mention the test double. Generated mocks are optional.
t.Run(name, func(t *testing.T)) starts a nested test. Failures are scoped to the name. -run TestParse/empty runs one child. Subtests can call t.Parallel independently.
A table-driven test is a slice of cases — input, want, name — and a loop that runs the same assertions on each. One test function covers many examples without copy-paste.
The testing package is the standard library's test harness. A function func TestFoo(t *testing.T) in a _test.go file is a test. t.Error, t.Fatal, t.Run, and t.Cleanup are how you fail, stop, nest, and tear down.
Breadth-first search visits a graph or tree level by level using a queue. The first time you reach a node is a shortest path in an unweighted graph.
Binary search finds a target in a sorted slice by repeatedly discarding half of the remaining range. It uses O(log n) comparisons. In Go you write the loop or call slices.BinarySearch / sort.Search.
Depth-first search explores a graph by going as deep as possible along one path, then backtracking. In Go you write a recursive walk or an explicit []T stack.
Dynamic programming solves a problem by storing answers to overlapping subproblems. In Go that is usually a slice or a map of memoized results, filled bottom-up or by a recursive function with a cache.
A greedy algorithm builds an answer by taking the locally best choice at each step. It is correct only when that local rule is proven to lead to a global optimum — or when you accept an approximation.
Heap algorithms use a binary heap to keep the current best element at the top: priority queues, top-K, and Dijkstra. In Go you implement heap.Interface on a slice, or keep a sorted slice when n is tiny.
A prefix-sum slice stores pref[i] = a[0] + ... + a[i-1]. Any subarray sum a[l] + ... + a[r-1] is then pref[r] - pref[l] in constant time after an O(n) preprocess.
A recursive function calls itself (or a partner function) on a smaller piece of the problem until it hits a base case. Each call has its own stack frame.
Searching a slice means finding an element or the first index that matches a condition. Linear search is a range. Binary search needs a sorted slice and sort.Search or slices.BinarySearch.
The slices package (Go 1.21+) is a generic toolkit for []T: sort, search, clip, compact, grow, delete, and compare. It replaces many sort.Slice and hand-rolled loops with typed helpers.
A sliding window maintains a contiguous subslice [left, right) that grows and shrinks as right advances. Each index enters and leaves the window at most once, so the scan is O(n).
The sort package sorts slices in place. sort.Ints, sort.Strings, and sort.Slice cover most code. sort.Interface is the older, explicit contract with Len, Less, and Swap.
Space complexity describes how extra memory an algorithm uses as the input grows. Auxiliary space usually excludes the input itself: an in-place swap is O(1) extra; a copy of the input is O(n).
Time complexity describes how the number of steps in an algorithm grows as the input grows. Big-O names the dominant term: O(1), O(n), O(n log n), O(n²).
Two pointers is a technique that walks a slice with a pair of indexes that only move forward (or from both ends). Each element is visited a constant number of times, so the extra work is O(n) after any required sort.
*sql.DB is a connection pool. It opens, reuses, and closes driver connections for you. SetMaxOpenConns, SetMaxIdleConns, and SetConnMaxLifetime are the knobs. You do not open a new DB per request.
database/sql is the standard library's generic SQL API. You open a *sql.DB with a driver name and DSN, then QueryContext, ExecContext, and PrepareContext. The package pools connections; it is not a dialect.
A SQL driver is a package that registers itself with database/sql so sql.Open(name, dsn) can dial a database. You import the driver for side effects: import _ "github.com/jackc/pgx/v5/stdlib".
Isolation is how much one transaction sees of others that have not committed. sql.TxOptions.Isolation sets the level when you BeginTx. The database still enforces the real rules; Go only sends the request.
A prepared statement is SQL with placeholders ($1, ?) that you send separately from the argument values. QueryContext(ctx, q, args...) prepares or binds those arguments. Concatenating user text into the query string is how you get SQL injection.
SQL injection is when untrusted text becomes part of a query's structure — a quote that ends a string and starts a new clause. In Go you prevent it by binding parameters, not by concatenating strings.
sqlx is a third-party layer on database/sql that scans rows into structs, supports named parameters, and keeps the same pool and context model. It is not an ORM.
A transaction groups statements so they commit together or roll back together. In database/sql, db.BeginTx returns a *sql.Tx. You Exec/Query on the Tx, then Commit or Rollback.
Request.Context() is a context cancelled when the client disconnects, the request times out, or the server shuts down. Pass it into store calls and outgoing HTTP. Do not use it for work that must continue after the handler returns.
CORS is a browser rule: a page on one origin may read a response from another only if the server lists that origin in Access-Control-Allow-Origin. In Go you set those headers in middleware, including on the OPTIONS preflight.
encoding/json converts Go values to JSON and back. Marshal/Unmarshal work on bytes. Encoder/Decoder work on streams. Struct tags control names.
An http.Handler has one method: ServeHTTP(http.ResponseWriter, *http.Request). http.HandlerFunc adapts a function to that interface. Everything that serves HTTP in Go is a handler.
An HTTP status code is the integer a handler sends with WriteHeader. The net/http package names the usual ones: StatusOK, StatusNotFound, StatusInternalServerError. The first write to the body implies 200 if you never called WriteHeader.
A JSON tag is a struct tag on a field that tells encoding/json the key name and options: ` json:"name,omitempty" `. Unexported fields are skipped even with a tag.
HTTP middleware is func(http.Handler) http.Handler that wraps a handler with cross-cutting behaviour: logs, auth, CORS, panic recovery, request IDs. The inner handler is next.
net/http is the standard library's HTTP client and server. http.ListenAndServe runs a server. http.Get and http.Client make requests. Handlers are http.Handler.
REST in a Go service means resources as URLs, HTTP methods as verbs, JSON as the body, and status codes as outcomes. net/http does not include a REST framework; you map paths on a mux and write handlers.
http.ServeMux maps request patterns to handlers. Since Go 1.22 it understands methods, wildcards ({id}), and trailing-slash redirects. It is the default router.
Escape analysis is the compiler's decision that a variable must live on the heap because a pointer to it (or the value itself) can outlive the function. If it cannot escape, the variable stays on the stack.
Go's garbage collector reclaims heap objects that are no longer reachable. You do not free. You still control how much garbage you create: allocations, leftover slice capacity, and lingering pointers.
A value copy duplicates the bits. A pointer shares one object. Choose a pointer when you need mutation or when the struct is large enough that copying shows up in a profile. Choose a value when the type is small and you want independent copies.
pprof is Go's profiling toolchain: the runtime/pprof and net/http/pprof packages write profiles, and the go tool pprof command visualizes them. Heap, CPU, goroutine, mutex, and block profiles are the usual views.
A slice header points at an array that actually holds the elements. Several slices can share one array. append may allocate a new array and leave old slices on the old one.
A slice leak is a small live header that keeps a large backing array reachable. len looks tiny; cap and the array are huge. The GC cannot free the unused tail.
Each goroutine has a stack for locals that do not escape. The heap holds values that outlive a frame or cannot be proven stack-safe. The compiler picks; you see the effect in allocations and GC.