Skip to main content

Go Fundamentals

Learning objectives
  • Explain zero values, slice headers, map semantics and string encoding precisely enough to predict program output.
  • Choose value vs pointer receivers and struct embedding deliberately, and justify the choice in review.
  • Model money, statuses and identifiers with named types instead of bare int64/string.
  • Explain how Go modules resolve versions (MVS), what the go and toolchain directives control, and how to keep private bank modules off public proxies.

TL;DR​

  • Every type has a zero value; good Go types make the zero value usable (sync.Mutex, bytes.Buffer) or deliberately invalid (StatusUnknown = 0).
  • A slice is a 3-word header (ptr, len, cap) over a backing array. append writes in place when there is spare capacity — two slices can silently share and overwrite memory.
  • Maps are reference-like, unordered, not safe for concurrent writes, and a nil map panics on write. A concurrent write is a fatal runtime error, not a recoverable panic.
  • Strings are immutable UTF-8 bytes: len counts bytes, range yields runes, slicing by byte index can cut a character in half.
  • Use pointer receivers when the method mutates, the struct is large, or it contains a lock; otherwise value receivers. Don't mix them on one type.
  • Embedding is composition with promotion, not inheritance: an embedding type is not a subtype of what it embeds.
  • The go line in go.mod is a language-semantics switch (e.g. per-iteration loop variables need go 1.22+), not just documentation.

Why it matters​

Fundamentals bugs are the ones that reach production because they look correct in review:

  • A batch settlement job builds per-merchant slices with append from a shared buffer. Two merchants end up with the same last line item because both slices share a backing array. Totals reconcile wrong by exactly one item — the kind of discrepancy that takes days to find in reconciliation.
  • A transfer description is truncated to 35 "characters" with desc[:35]. For Vietnamese text like "Chuyển tiền học phí", that cuts a multi-byte rune and the downstream ISO 20022 / core-banking system rejects invalid UTF-8.
  • A float64 amount field drifts by fractions of a cent across millions of transactions, breaking double-entry invariants.
  • A cache map is read and written from HTTP handlers during a flash sale; under load the process dies with fatal error: concurrent map writes — no recover can save it.

Interviewers for senior Go roles use these exact cases to separate people who use Go from people who understand its memory model and data layout.

Core concepts​

Types and zero values​

Go initialises every variable to its type's zero value. There is no "uninitialised" state.

TypeZero valueNote
int, int64, float640
boolfalse
string""not nil; strings can't be nil
pointer, slice, map, chan, func, interfacenilnil slice is usable for len, range, append
structeach field zeroedrecursively
array [N]TN zero Tsarrays are values (copied on assignment)

Two design rules follow:

  1. Make the zero value useful where you can. var mu sync.Mutex and var buf bytes.Buffer work without constructors. A Config struct whose zero value means "sane defaults" is easier to test.
  2. Make the zero value invalid when a default would be dangerous. For a payment status, a zero that means Captured is a bug waiting to happen; make 0 mean "unknown" so a forgotten assignment is detectable.
package payment

import "fmt"

// Status is a payment lifecycle state. The zero value is deliberately invalid.
type Status uint8

const (
StatusUnknown Status = iota
StatusPending
StatusAuthorized
StatusCaptured
StatusFailed
)

func (s Status) String() string {
switch s {
case StatusPending:
return "pending"
case StatusAuthorized:
return "authorized"
case StatusCaptured:
return "captured"
case StatusFailed:
return "failed"
default:
return fmt.Sprintf("Status(%d)", uint8(s))
}
}

// Valid reports whether s is a known, non-zero status.
func (s Status) Valid() bool { return s >= StatusPending && s <= StatusFailed }

go generate with golang.org/x/tools/cmd/stringer produces the String method for you. Since Go 1.24 you can pin such tools in go.mod with a tool directive and run them via go tool stringer.

Named types for domain safety​

type AccountID string and type Currency string are defined types: distinct from string, so the compiler rejects passing a Currency where an AccountID is expected. A type alias (type A = B) is just another name for the same type and gives no safety — aliases exist for refactoring across packages. (Generic type aliases became fully supported in Go 1.24.)

Money is the canonical example. Never use float64 — binary floating point cannot represent 0.10 exactly. Use integer minor units plus a currency:

package money

import (
"errors"
"fmt"
)

// Currency is an ISO 4217 code such as "VND" or "USD".
type Currency string

// Money is an amount in minor units (cents for USD; VND has no minor unit).
type Money struct {
Amount int64
Currency Currency
}

var (
ErrCurrencyMismatch = errors.New("money: currency mismatch")
ErrOverflow = errors.New("money: overflow")
)

// Add returns m+o. Money is a small immutable value, so a value receiver fits.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, fmt.Errorf("%w: %s vs %s", ErrCurrencyMismatch, m.Currency, o.Currency)
}
sum := m.Amount + o.Amount
if (sum > m.Amount) != (o.Amount > 0) { // signed overflow wrapped around
return Money{}, ErrOverflow
}
return Money{Amount: sum, Currency: m.Currency}, nil
}

Go integer overflow wraps silently — no exception — so ledger code must check it explicitly. See Schema Patterns: Money, Audit, Multi-tenancy for the storage side.

Slices: header, backing array, aliasing​

A slice value is a small struct: pointer to the first element, length, capacity. Passing a slice to a function copies the header, not the elements — callee and caller share the backing array.

append(s, x) behaves in one of two ways:

  • len(s) < cap(s): writes x into the existing array at index len(s) and returns a header with len+1. Every other slice sharing that array sees the write.
  • len(s) == cap(s): allocates a new, larger array, copies, then writes. The result no longer aliases the input.

So whether two slices alias depends on runtime capacity — the worst kind of bug, because it appears only for some input sizes.

base := make([]int, 3, 4) // [0 0 0 _], cap 4
a := append(base, 1) // fits: writes base's array[3] = 1
b := append(base, 2) // fits: overwrites array[3] = 2
fmt.Println(a[3], b[3]) // 2 2 — a was silently changed

A realistic version in payments code:

// BUG: if the caller passes a sub-slice with spare capacity,
// the fee overwrites the caller's next element.
func withFee(items []LineItem, fee LineItem) []LineItem {
return append(items, fee)
}

// Fix 1: force a copy by capping capacity (full slice expression s[lo:hi:max]).
func withFeeSafe(items []LineItem, fee LineItem) []LineItem {
return append(items[:len(items):len(items)], fee)
}

// Fix 2 (Go 1.21+): be explicit.
func withFeeClone(items []LineItem, fee LineItem) []LineItem {
return append(slices.Clone(items), fee)
}

Growth policy: when append reallocates, capacity roughly doubles for small slices, then grows by a smaller factor that trends toward ≈1.25× for large ones (the formula was smoothed in Go 1.18), rounded up to an allocator size class. Never depend on exact capacities. If you know the final size, preallocate: out := make([]Txn, 0, len(rows)).

Other slice facts worth knowing cold:

  • Retention: header := buf[:16] keeps the whole buf (maybe 10 MB) alive. Copy what you keep: bytes.Clone(buf[:16]) (Go 1.20+).
  • nil vs empty: both have len 0 and work with append, but encoding/json marshals a nil slice as null and []T{} as []. Pick one for your API contract and test it.
  • copy(dst, src) copies min(len(dst), len(src)) elements and handles overlap.
  • Arrays are values. [32]byte (e.g. a SHA-256 digest) is copied on assignment and is comparable, so it works as a map key; a slice is not comparable.
  • Since Go 1.21 the slices package covers Sort, BinarySearch, Contains, Index, Compact, Equal, Clone, Grow, Clip; prefer it to hand-rolled loops.

Maps​

A map value is a pointer to a runtime hash table, so passing a map to a function lets it mutate the caller's map.

  • Reading a missing key returns the zero value; use comma-ok to distinguish: bal, ok := balances[id].
  • Writing to a nil map panics. Initialise with make(map[K]V, hint) or a literal.
  • Iteration order is deliberately randomised. Sort keys (slices.Sorted(maps.Keys(m)), Go 1.23+) when output order matters — reports, signatures, hashes.
  • Deleting during range is safe; adding during range may or may not be visited.
  • Map elements are not addressable: m[k].Balance += 10 doesn't compile when the value is a struct. Store pointers or read-modify-write the whole value.
  • Maps do not shrink when you delete; a map that once held 1M sessions keeps that memory. Rebuild it (copy live entries into a new map) to release it. clear(m) (Go 1.21) empties it but keeps capacity.
  • Not safe for concurrent use. Concurrent writes, or a write concurrent with a read, may trigger fatal error: concurrent map writes — this kills the process and cannot be recovered. Guard with a sync.Mutex/RWMutex or use sync.Map for its specific use cases (see sync, atomic & context).
  • Go 1.24 replaced the map implementation with one based on Swiss tables — faster lookups and inserts in most workloads, same semantics. Your code doesn't change; benchmarks might.

Key types must be comparable: no slices, maps or funcs. Structs of comparable fields work well as composite keys: map[struct{ Merchant, Day string }]int64.

Strings, bytes and runes​

A string is an immutable sequence of bytes, conventionally UTF-8. A rune is an int32 Unicode code point. A []byte is mutable.

name := "Nguyễn"
fmt.Println(len(name)) // 8 — bytes ("ễ" is 3 bytes in UTF-8)
fmt.Println(utf8.RuneCountInString(name)) // 6 — code points
for i, r := range name { // i = byte offset, r = rune
fmt.Printf("%d:%c ", i, r)
}
fmt.Println(utf8.ValidString(name[:5])) // false — cut inside "ễ"

Things that bite in banking and e-commerce:

  • Truncation: field limits ("max 35 characters" on a transfer memo) are usually in characters, sometimes in bytes. Truncate on rune boundaries ([]rune(s)[:n] or walk with utf8.DecodeRuneInString), and confirm which unit the downstream system counts.
  • Normalisation: "ễ" can be one precomposed code point (NFC) or "e" plus two combining marks (NFD). They render the same but compare unequal and have different byte lengths (8 vs 10 bytes for "Nguyễn"). Normalise names with golang.org/x/text/unicode/norm before matching against sanctions/KYC lists.
  • Conversions copy: []byte(s) and string(b) allocate in general. The compiler optimises some cases (map lookup m[string(b)], comparisons, for range []byte(s)). Build strings with strings.Builder, not += in a loop.
  • Case-insensitive comparison: strings.EqualFold, not strings.ToLower(a) == strings.ToLower(b) (allocates and is wrong for some scripts).

Structs and embedding​

Structs are values: assignment copies all fields. A struct whose fields are all comparable is comparable with ==.

Embedding a type promotes its fields and methods to the outer type:

type Audit struct {
CreatedAt time.Time
CreatedBy string
}

func (a *Audit) Stamp(by string, now time.Time) {
a.CreatedAt, a.CreatedBy = now, by
}

type Transfer struct {
Audit // embedded: t.CreatedAt and t.Stamp(...) are promoted
ID string
Amount money.Money
}

t.Stamp("ops", now) is shorthand for t.Audit.Stamp(...). But a Transfer is not an Audit: you cannot pass it to func f(a Audit). The receiver inside Stamp is the embedded Audit, never the Transfer, so there is no virtual dispatch back to the outer type. If the outer type declares a field or method with the same name, it shadows the promoted one. Embedding is covered as a composition tool in Interfaces & Composition.

Struct tags (json:"amount", db:"amount_minor") are just strings read via reflection. Since Go 1.24 encoding/json supports omitzero, which omits zero values using IsZero() when present — handy for time.Time, which omitempty never omitted.

Methods: value vs pointer receivers​

Declared asIn method set of TIn method set of *T
func (t T) M()yesyes
func (t *T) M()noyes

You can call a pointer method on an addressable value (v.M() becomes (&v).M()), which hides the rule until you try to satisfy an interface: if Save has a pointer receiver, only *Repo implements Saver, and var s Saver = Repo{} fails to compile.

Choose a pointer receiver when:

  • the method mutates the receiver;
  • the type contains a sync.Mutex, sync.WaitGroup, or other state that must not be copied (go vet's copylocks check catches many cases);
  • the struct is large (rough rule: more than a few words) and copying it on every call is wasteful.

Choose a value receiver for small immutable values (Money, time.Time, Status) and for types that are already references (maps, funcs, chans). Keep receivers consistent on a type — mixing them confuses readers and method sets.

Packages and visibility​

  • Identifiers starting with an upper-case letter are exported from the package; everything else is package-private. There is no protected.
  • A directory named internal restricts imports to code rooted at its parent — enforced by the toolchain. Use it to stop other teams depending on your adapters (see Project Layout & Clean Architecture in Go).
  • Import cycles are compile errors. They usually reveal a missing abstraction: move the shared type down a layer or invert the dependency with an interface.
  • Package names are short, lower-case, singular, and part of the call site: payment.New, not payment.NewPaymentService. Avoid util, common, helpers.
  • Avoid init() side effects (DB connections, flag parsing, global registration) — they run at import time, in dependency order, and make tests order-dependent.

Modules​

module gitlab.bank.internal/payments/transfer-svc

go 1.24

toolchain go1.26.2

require (
github.com/jackc/pgx/v5 v5.7.4
golang.org/x/sync v0.12.0
)

tool golang.org/x/tools/cmd/stringer
  • Module path is the import prefix. Major versions 2+ change the path (/v2) — semantic import versioning — so v1 and v2 can coexist in one build.
  • Minimal Version Selection (MVS): for each module, Go picks the highest of the minimum versions required anywhere in the graph — never "latest". Builds are reproducible without a lock file; go.sum holds cryptographic hashes, not version choices.
  • go directive: since Go 1.21 it is a minimum requirement, and it selects language semantics. Per-iteration loop variables (Go 1.22) and the timer changes (Go 1.23) only apply when this line is new enough.
  • toolchain directive (Go 1.21+) lets the go command download a newer toolchain automatically.
  • Private code: set GOPRIVATE=gitlab.bank.internal/* so module paths and source never go to proxy.golang.org or the public checksum database — a real data-leak concern in regulated environments. Many banks run an internal proxy (Athens, Artifactory) and set GOPROXY to it.
  • Workspaces (go work, Go 1.18+) let you develop several modules together locally without replace directives leaking into commits.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Value receiverNo aliasing, safe to copy, can live on the stackCopies on each call; mutation is lostSmall immutable values: Money, IDs, enums
Pointer receiverMutation, no copy, required with locksNil receiver possible, shared mutable stateEntities, services, anything with a mutex
Slice of structs []TContiguous, cache-friendly, few allocationsCopies on range; &s[i] invalidated by reallocationHot loops, batches
Slice of pointers []*TCheap to reorder, stable addressesOne allocation per element, GC pressure, pointer chasingLarge or shared elements
map[K]V lookupO(1) averageMemory overhead, random order, no concurrencyLarge sets, frequent lookups
Linear scan of a small sliceOften faster below ≈ tens of elements, deterministic orderO(n)Tiny fixed sets (currencies, statuses)
stringImmutable, comparable, safe to shareConversions allocateKeys, identifiers, API fields
[]byteMutable, reusable buffersNot a map key, aliasing riskI/O, parsing, building payloads

In practice​

  • Preallocate in batch jobs: make([]Entry, 0, len(rows)) avoids repeated growth. slices.Grow (Go 1.21) reserves capacity on an existing slice.
  • Return copies from caches. If a cache returns its internal slice, callers can mutate cached state. Return slices.Clone(v) or immutable types.
  • Composite map keys as structs instead of string concatenation (merchant + "|" + day) — no allocation, no delimiter collisions.
  • Constructors when invariants exist. NewTransfer(from, to AccountID, amt money.Money) (*Transfer, error) validates once; the zero Transfer should not be usable for posting.
  • Pin language semantics: keep the go line current and run go vet ./... in CI; vet's copylocks, printf, loopclosure and stdmethods checks catch fundamentals bugs cheaply.

Range over integers (Go 1.22) tidies retry loops:

for attempt := range 3 { // 0, 1, 2
if err := publish(ctx, evt); err == nil {
break
}
time.Sleep(backoff(attempt))
}

Common pitfalls​

  • Append aliasing — two results of append on the same base overwrite each other. Symptom: occasional duplicated or wrong last element. Fix: full slice expression or slices.Clone.
  • Writing to a nil map inside a struct whose constructor forgot make. Symptom: panic: assignment to entry in nil map.
  • Holding &s[i] across an append — after reallocation the pointer refers to the old array; updates are lost.
  • Range copies values: for _, a := range accounts { a.Balance += 1 } updates a copy. Use the index: accounts[i].Balance += 1.
  • Byte-slicing UTF-8 text — invalid UTF-8 in statements, SMS, or JSON. Truncate by rune.
  • Float money — rounding drift; failed reconciliations.
  • Mixed receivers — the type unexpectedly doesn't satisfy an interface, or a mutex gets copied by a value-receiver method (vet: "passes lock by value").
  • init() doing I/O — tests fail without network; startup order surprises.
  • Large sub-slice retention — heap grows although "only 16 bytes" are kept.

Interview angle​

Typical questions: "What does this program print?" (append aliasing, range copies), "Why is this map write crashing?", "Value or pointer receiver here, and why?", "How would you represent money in Go?", "How does Go pick dependency versions?"

A strong answer draws the slice header, states the two append cases, and names the fix. For money, say "int64 minor units plus ISO currency, overflow checks, banker's or explicit rounding at defined boundaries, NUMERIC in the database", and mention why float64 fails. For modules, explain MVS and why it gives reproducible builds without a lock file.

Follow-ups to expect: "What happens to a slice passed to a function that appends?", "Why can't you take the address of a map element?", "What does the go directive change?", "How do you keep internal module paths private?"

Red flags: "slices are passed by reference", "maps are thread-safe for reads so it's fine", using float64 for amounts, or believing embedding gives polymorphism.

Self-check​

1. A function receives items []LineItem and does items = append(items, fee). When does the caller observe the change, and how do you make it never happen?

The caller's slice header (len) never changes, but if len < cap the append writes into the shared backing array, so any caller slice that spans that index sees the fee. If capacity is full, a new array is allocated and the caller is unaffected. Make it deterministic with append(items[:len(items):len(items)], fee) or slices.Clone before appending.

2. Why does m["acc-1"].Balance += 100 fail to compile when m is map[string]Account, and what are the two fixes?

Map elements are not addressable — the runtime may move them as the table grows, so Go forbids taking their address or assigning to their fields. Either store pointers (map[string]*Account) or read, modify and write back: a := m[k]; a.Balance += 100; m[k] = a.

3. len("Nguyễn") is 8 but a colleague's test with the same visible name gets 10. Explain.

The colleague's string is in NFD form: "e" plus combining circumflex and combining tilde (2 bytes each) instead of the precomposed "ễ" (3 bytes). They render identically but differ in bytes and compare unequal. Normalise both sides (NFC) with golang.org/x/text/unicode/norm before comparing names.

4. When should a type use pointer receivers, and what goes wrong if a type with a sync.Mutex uses value receivers?

Pointer receivers when methods mutate state, the struct is large, or it holds a lock or other no-copy state. With value receivers, each call locks a copy of the mutex, so there is no mutual exclusion at all — a data race. go vet reports "passes lock by value".

5. Your service requires lib A (needs x v1.3) and lib B (needs x v1.5); x v1.9 is the latest. What version is built, and why is that a deliberate design choice?

v1.5: MVS chooses the highest of the minimum required versions. It never picks a version nobody asked for, so builds are reproducible and upgrades happen only when someone edits a go.mod — no surprise upgrades on a Friday deploy.

6. Scenario: an API returns "items": null to a mobile app that crashes on null. What Go detail caused it and how do you fix it at the source?

A nil slice marshals to JSON null; an empty non-nil slice marshals to []. Initialise with items := []Item{} (or make([]Item, 0, n)) in the response DTO and add a contract test that asserts [].

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Build a tiny money + ledger package:

  1. Implement Money with Add, Sub, Neg, and Allocate(parts int) []Money, which splits an amount into parts shares that sum exactly to the original (e.g. 100 VND across 3 parties gives 34, 33, 33).
  2. Implement type Ledger struct holding []Entry and a map[AccountID]int64 of balances, with Post(debit, credit AccountID, amt Money) error that rejects currency mismatches and overflow.
  3. Write a test that proves Post never aliases a caller-provided []Entry (pass a sub-slice with spare capacity and assert the caller's next element is untouched).
  4. Add func (l *Ledger) Statement(id AccountID) []Entry returning a copy, and a test that mutating the result doesn't change the ledger.

Done when: go test -race ./... passes, go vet ./... is clean, and Allocate is covered by a table-driven test including negative amounts and parts = 1. Compare your approach with the labs in Hands-on Go Labs.

Further reading​

  • Effective Go and Go Code Review Comments — official, at go.dev.
  • The Go Programming Language Specification — sections on types, method sets, and assignability.
  • Go blog: "Go Slices: usage and internals" (Andrew Gerrand) and "Arrays, slices (and strings): The mechanics of 'append'" (Rob Pike).
  • Go blog: "Strings, bytes, runes and characters in Go" (Rob Pike).
  • Go Modules Reference (go.dev/ref/mod), including Minimal Version Selection; Russ Cox's "Minimal Version Selection" essay.
  • Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — chapters on slices, maps and strings.
  • Alan Donovan & Brian Kernighan, The Go Programming Language.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).