Cheatsheet
Fast one-page lookup: everyday Go syntax and idioms up top, then the verified build/test/CLI commands and directory layout of a real Go system — multigres (“Vitess for Postgres”) — below. Each row links into the language and project tracks for depth.
Go syntax
Section titled “Go syntax”Declarations
Section titled “Declarations”| Form | Example | Notes |
|---|---|---|
var | var n int | zero value (0, "", nil) |
:= | n := 42 | short, function-scope only |
const | const Max = 1 << 20 | compile-time |
iota | const ( A = iota; B; C ) | 0,1,2 enum counter |
| multi | a, b := 1, 2 | tuple assign / swap a, b = b, a |
Slices
Section titled “Slices”s := make([]int, 0, 8) // len 0, cap 8s = append(s, 1, 2) // grow (may realloc)n := copy(dst, src) // n = min(len(dst), len(src))s = s[2:5] // sub-slice (shares backing array)clear(s) // zero all elements (Go 1.21+)A sub-slice shares the backing array — appending into it can clobber the parent. See stdlib & idioms.
v, ok := m[k] // comma-ok: ok=false if absentdelete(m, k) // no-op if absentfor k, v := range m { ... } // unorderedclear(m) // remove all keysError pattern
Section titled “Error pattern”if err != nil { return nil, fmt.Errorf("doing X: %w", err) // wrap with %w}errors.Is(err, target) / errors.As(err, &t) to inspect. Depth: errors. In this codebase, errors at RPC/service boundaries use mterrors, not bare fmt.Errorf — see the mterrors section below.
Goroutine / channel / select
Section titled “Goroutine / channel / select”go work() // fire-and-forget goroutinech := make(chan int, 4) // buffered (cap 4); unbuffered if no capch <- v // sendv, ok := <-ch // receive; ok=false when closed and drainedclose(ch) // sender closes, never the receiver
select {case v := <-ch: ...case ch2 <- x: ...case <-ctx.Done(): return ctx.Err() // cancellationdefault: ... // non-blocking}Depth: concurrency.
Context
Section titled “Context”func Do(ctx context.Context, ...) error { // ctx is always the FIRST param ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() // always defer cancel ...}Depth: context.
Struct tags
Section titled “Struct tags”type Config struct { Name string `json:"name"` Port int `json:"port,omitempty"`}Backtick-quoted key:"value" metadata read by reflection (encoding, validation). Depth: stdlib & idioms.
Generics
Section titled “Generics”func Map[T, U any](s []T, f func(T) U) []U { ... }type Group[K comparable, V any] struct { ... } // K must be comparableany = interface{}; comparable = usable with ==. A real example: func NewGroup[K comparable, V any]() *Group[K, V] in the codebase’s singleflight cache. Depth: generics.
defer / recover
Section titled “defer / recover”defer f() // runs at function return, LIFO orderdefer func() { if r := recover(); r != nil { ... } // recover only inside a deferred func}()Deferred args are evaluated when defer runs, not when the function returns.
Real-world commands
Section titled “Real-world commands”The examples below come from multigres: Go 1.25, a single module github.com/multigres/multigres, all code under go/. The build is Makefile-driven; make help auto-generates the target list from ## comments — a tidy pattern worth borrowing.
Make targets
Section titled “Make targets”| Target | Does |
|---|---|
make tools | Install protobuf + build tools |
make build | Build all 7 binaries into bin/ (debug, with symbols) |
make build-release | Static, stripped release binaries (CGO_ENABLED=0) |
make build-all | proto + parser + metrics + build |
make proto | Regenerate protobuf into go/pb |
make parser | go generate the SQL parser: goyacc and asthelpergen |
make metrics | Generate the Prometheus metric catalog |
make generate | Alias for parser + metrics (NOT proto) |
make install | Install binaries to GOPATH/bin |
make test | Run all tests (starts the port-pool server) |
make test-short | Short tests only |
make test-race | Tests with the race detector |
make test-coverage | Comprehensive coverage |
make clean / make clean-all | Remove build artifacts / + deps |
make validate-generated-files | CI check: regenerate everything and diff |
make pgregress / pgexternal / pgproto | PostgreSQL regression / external-ext / wire-protocol suites |
The 7 binaries are multigateway, multipooler, pgctld, multiorch, multigres, multiadmin, and portpoolserver, each built via go build -o bin/$cmd ./go/cmd/$cmd.
Running tests
Section titled “Running tests”This codebase runs its tests through a dev wrapper rather than calling go test directly — integration runs need a shared port pool, or they collide flakily. The wrapper expands to ordinary go test invocations:
| Invocation | Expands to |
|---|---|
unit all | go test -short ./go/... |
unit <pkg> [TestName] | go test [-run TestName] <pkg> |
integration all | make build && go test ./go/test/endtoend/... |
integration <pkg> [TestName] | make build + start port pool + go test [-run TestName] ./go/test/endtoend/<pkg>/... |
Integration <pkg> values: all, multipooler, multiorch, queryserving, localprovisioner, shardsetup, pgregresstest. Common flags: -v -race -cover -count=N -short -timeout.
multigres CLI (local cluster)
Section titled “multigres CLI (local cluster)”The multigres binary doubles as the cluster-management CLI:
| Command | Does |
|---|---|
./bin/multigres cluster init | Initialize cluster config |
./bin/multigres cluster start | Start local cluster components |
./bin/multigres cluster stop [--clean] | Stop (--clean wipes state) |
./bin/multigres cluster status | Show component status |
./bin/multigres getpoolers | List registered poolers |
./bin/multigres getpoolerstatus --cell <cell> --service-id <id> | Status of one pooler |
Depth: cmd & cobra.
Errors — mterrors
Section titled “Errors — mterrors”Project error constructors (where code is a protobuf RPC code):
mterrors.New(code, message)mterrors.Errorf(code, format, args...)mterrors.Wrap(err, message)mterrors.Wrapf(err, format, args...)mterrors.NewPgError(...) // Postgres wire errorsUse these at RPC/service boundaries; reserve stdlib fmt.Errorf("...: %w", err) for internal wrapping. Depth: mterrors & observability.
Key directories
Section titled “Key directories”Directorygo/
Directorycmd/ entrypoints for the 7 binaries
- …
Directoryservices/ service impls: multiadmin, multigateway, multiorch, multipooler, pgctld
- …
Directorycommon/ shared libs: mterrors, parser, pgprotocol, sqltypes, consensus, servenv, …
- …
Directorypb/ generated protobuf (output of
make proto)- …
Directoryobservability/ generated metric catalog (output of
make metrics)- …
Directorytest/endtoend/ integration tests
- …
Directoryproto/ proto source files
- …
See also
Section titled “See also”- Orientation
- Glossary — terms
- Idioms and gotchas
- Further reading
- Language: errors, generics, concurrency, context, stdlib & idioms
- Project: cmd & cobra, grpc & protobuf, mterrors & observability
- Tooling: build & make, testing workflow, modules, deps & codegen