Skip to content

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 — the example system, a distributed SQL proxy — below. Each row links into the language and project tracks for depth.

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
s := make([]int, 0, 8) // len 0, cap 8
s = 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 absent
delete(m, k) // no-op if absent
for k, v := range m { ... } // unordered
clear(m) // remove all keys
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 the project’s structured-error package errx, not bare fmt.Errorf — see the errx section below.

go work() // fire-and-forget goroutine
ch := make(chan int, 4) // buffered (cap 4); unbuffered if no cap
ch <- v // send
v, ok := <-ch // receive; ok=false when closed and drained
close(ch) // sender closes, never the receiver
select {
case v := <-ch: ...
case ch2 <- x: ...
case <-ctx.Done(): return ctx.Err() // cancellation
default: ... // non-blocking
}

Depth: concurrency.

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.

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.

func Map[T, U any](s []T, f func(T) U) []U { ... }
type Group[K comparable, V any] struct { ... } // K must be comparable

any = 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 f() // runs at function return, LIFO order
defer func() {
if r := recover(); r != nil { ... } // recover only inside a deferred func
}()

Deferred args are evaluated when defer runs, not when the function returns.

The examples below come from the example system: Go 1.25, a single module github.com/example/platform, laid out in the standard cmd/ + internal/ style. The build is Makefile-driven; make help auto-generates the target list from ## comments — a tidy pattern worth borrowing.

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 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 gateway, pooler, dbctld, orchestrator, platformctl, admin, and portpoolserver, each built via go build -o bin/$cmd ./cmd/$cmd.

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 ./...
unit <pkg> [TestName] go test [-run TestName] <pkg>
integration all make build && go test ./test/endtoend/...
integration <pkg> [TestName] make build + start port pool + go test [-run TestName] ./test/endtoend/<pkg>/...

Integration <pkg> values: all, pooler, orch, queryserving, localprovisioner, shardsetup, pgregresstest. Common flags: -v -race -cover -count=N -short -timeout.

The platformctl binary doubles as the cluster-management CLI:

Command Does
./bin/platformctl cluster init Initialize cluster config
./bin/platformctl cluster start Start local cluster components
./bin/platformctl cluster stop [--clean] Stop (--clean wipes state)
./bin/platformctl cluster status Show component status
./bin/platformctl getpoolers List registered poolers
./bin/platformctl getpoolerstatus --cell <cell> --service-id <id> Status of one pooler

Depth: cmd & cobra.

Project error constructors (where code is a protobuf RPC code), from the project’s structured-error package:

errx.New(code, message)
errx.Errorf(code, format, args...)
errx.Wrap(err, message)
errx.Wrapf(err, format, args...)
errx.NewPgError(...) // Postgres wire errors

Use these at RPC/service boundaries; reserve stdlib fmt.Errorf("...: %w", err) for internal wrapping. Depth: errors & observability.

  • Directorycmd/ entrypoints for the 7 binaries
  • Directoryinternal/
    • admin, gateway, orch, pooler, dbctld service impls
    • errx, parser, pgprotocol, sqltypes, consensus, servenv, … shared libs
  • Directorypb/ generated protobuf (output of make proto)
  • Directoryobservability/ generated metric catalog (output of make metrics)
  • Directorytest/endtoend/ integration tests
  • Directoryproto/ proto source files