Pointers & Memory Model Basics
"Without pointer arithmetic it's possible to create a language that can never derive an illegal address that succeeds incorrectly." — The Go FAQ, Why is there no pointer arithmetic?
Summary: A Go pointer is a typed address you can copy, compare and dereference but never add to; the compiler decides whether the value lives on the stack or the heap, and a concurrent garbage collector frees it when nothing points to it any more. Focus: &, * and new, nil dereference panics, pointer versus value receivers, when pointers are the right tool, escape analysis (-gcflags=-m), the garbage collector and its knobs (GOGC, GOMEMLIMIT), struct padding, *string for optional fields, atomic.Pointer[T], unsafe.Pointer and uintptr, the Go memory model, runtime.KeepAlive, runtime.AddCleanup and profiling with pprof. Learning goal: Decide for every variable whether it should be a value or a pointer, predict where it is allocated, read a nil-pointer panic, shrink a struct by reordering fields, and know exactly which unsafe tricks are legal.
This page is the complete reference for pointers and for the memory model a Go programmer needs: what a pointer is, where values live, how they are freed and how goroutines see each other's writes. It owns the language mechanics. Methods and receivers in depth are in Structs, Methods, Constructors, Embedding & Struct Tags; slices and maps as headers over shared memory are in Arrays, Slices & Maps; the race detector, mutex bugs and deadlocks are in Race Conditions, the Race Detector, Deadlocks, Concurrency vs Parallelism; sync and atomic counters are in sync & atomic; struct tags and the JSON encoder are in JSON, XML, Struct Tags, Encoder/Decoder, Base64. Here you get the one model that ties them together.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has pointers but no arithmetic | Why it exists |
| Spec, FAQ, memory model, GC history | Where it comes from |
&, *, new, zero value nil | Pointer basics |
panic: runtime error: invalid memory address | Nil pointers |
| Copy versus share, receivers | Pointer and value receivers |
| Mutation, big structs, optional, identity | When to use a pointer |
| Slices, maps, channels are already references | Reference-like types |
&v in a for loop | Pointer to a loop variable |
*string and JSON | Optional fields |
Stack versus heap, moved to heap | Escape analysis |
GOGC, GOMEMLIMIT, write barrier, pauses | The garbage collector |
Padding, unsafe.Sizeof, field order | Memory layout |
atomic.Pointer[T] | Atomic pointers |
unsafe.Pointer and uintptr | unsafe |
| Happens-before, data races | The memory model |
Finalizers, AddCleanup, KeepAlive | Cleanups |
| pprof heap and allocation profiles | Profiling memory |
| PHP references, handles, copy-on-write | For PHP/Laravel developers |
| Reproduce the outputs | Lab |
Everything in one minute
The operators.
| Syntax | In plain words | Example | Result |
|---|---|---|---|
&x | Address of the variable x | p := &x | p has type *int |
*p | The value p points to (dereference) | *p = 4 | x becomes 4 |
*T | Type: pointer to T | var p *int | zero value is nil |
new(T) | Allocate a zero T, return its address | p := new(int) | same as &T{} for structs |
p.f | Field through a pointer (auto-dereference) | c.N | same as (*c).N |
p == nil | Pointer points nowhere | if c == nil | safe, no panic |
p + 1 | Does not exist | compile error | no pointer arithmetic |
The decisions.
| Question | Value | Pointer |
|---|---|---|
| Must the callee change the caller's variable? | no | yes |
| Is the struct large or contains a mutex? | small, copyable | large, or must never be copied |
| Can the value be absent? | use a zero value or ok | *T is nil when absent |
| Do two holders need to see the same object? | no | yes (identity) |
| Is it a map, slice, channel, func or interface? | pass by value | rarely a pointer |
The memory facts.
| Fact | Detail |
|---|---|
| Stack versus heap | The compiler chooses by escape analysis, not by new versus & |
| Collector | Concurrent, non-generational, non-moving, tri-color mark and sweep |
| Main knobs | GOGC (default 100) and GOMEMLIMIT (default off) |
| Struct size | Sum of fields plus padding; order fields large to small |
| Data race | Undefined-ish: the memory model only promises behaviour for race-free programs |
uintptr | An integer, not a reference: the GC ignores it |
Why it exists
Passing everything by copy is safe but slow for big values and useless when a function must change something. Passing everything by reference (as Java does for objects) hides who can mutate what. Go gives you both, explicitly: values are copied, pointers are shared, and you see the * and & at the call site and in the type.
| Weaker, simpler | Stronger, richer |
|---|---|
| Value semantics: copy on assignment, no aliasing | Pointer semantics: one object, many holders |
| No pointer arithmetic: no buffer overruns through index maths | unsafe available, but fenced off and named |
Garbage collection: no free, no use-after-free | You pay in GC CPU and some latency |
An everyday picture. A value is a photocopy of a document: change your copy and nobody else notices. A pointer is the document's shelf address written on a sticky note: everyone holding the note walks to the same page. A nil pointer is a note with no address. Writing p.N on it is walking to a door that does not exist.
Three common misunderstandings, up front
- "
newallocates on the heap and&xon the stack." Wrong. Where a value lives is decided by escape analysis (Escape analysis);new(int)that never leaves the function stays on the stack. - "Pointers make Go faster." Often the opposite: a pointer can force a heap allocation and gives the garbage collector more to scan. Small values are cheaper copied.
- "Maps and slices need
*to be modified by a function." A map is a handle to shared data and a slice is a header pointing at shared data; element writes show through. Only changing the slice header itself (appendresult) needs the caller to take the return value or a*[]T.
Where it comes from
The authoritative texts are the Go specification (pointer types, address operators, selectors, zero values), Effective Go (allocation with new and make), the Go FAQ (no pointer arithmetic, "Should I define methods on values or pointers?", "How do I know whether a variable is allocated on the heap or the stack?"), and The Go Memory Model (happens-before). The runtime side is told in the GC guide and in the ISMM keynote "Getting to Go", which describes the decision to build a tri-color concurrent collector and the write barrier it needs. The AddCleanup function arrived in the Go 1.24 release notes; the per-iteration loop variable in Go 1.22.
The FAQ gives the reasons for the design: safety first, and "the lack of pointer arithmetic can simplify the implementation of the garbage collector". A collector that must find every pointer cannot let programs manufacture pointers from integers.
The concept catalogue
Pointer basics: &, *, new Must-know
In plain words: &x gives you where x lives; *p follows that address to read or write the value. new(T) makes a fresh zero T and hands back its address.
Common misunderstanding: "p2 := p copies the thing." It copies the address. Both pointers now name the same variable, so a write through one is visible through the other.
Definition: For an addressable operand x of type T, &x has type *T. For p of type *T, *p denotes the variable p points to; if p is nil the evaluation panics at run time (spec, "Address operators"). The zero value of any pointer type is nil. Pointer values are comparable with ==, equal when they point to the same variable or both nil.
1 x := 10
2 p := &x // p -> x
3 q := p // q -> x too (address copied)
4 *q = 20 // x is now 20
5 fmt.Println(*p) // 20
6 r := new(int) // r -> fresh zero int
7 fmt.Println(*r, p == q, p == r) // 0 true falseReal scenario: a function that fills a result struct passed by the caller (json.Unmarshal(data, &cfg)); a sql.Rows.Scan(&id, &name) that writes into your variables; a constructor NewServer() *Server.
| Form | Meaning | Note |
|---|---|---|
&x | Address of an addressable variable | Not of map elements or function results |
&T{...} | Address of a fresh composite literal | The usual constructor form |
new(T) | Pointer to a zero T | Rare; &T{} is clearer |
*p | Dereference | Panics if nil |
p.f, p.M() | Auto-dereference for fields and methods | No -> operator |
Fix / how to use it: the snippet below shows the three operators, nil checks and the panic converted into an error. The tests assert each behaviour.
// Package basics shows &, *, new, nil pointers and value vs pointer receivers.
package basics
import "fmt"
// Counter is a small struct used to compare receivers.
type Counter struct{ N int }
// IncValue changes a copy; the caller sees nothing.
func (c Counter) IncValue() { c.N++ }
// IncPtr changes the original through the pointer.
func (c *Counter) IncPtr() { c.N++ }
// Bump receives a copy of the int; the caller's variable is untouched.
func Bump(n int) { n++ }
// BumpPtr writes through the pointer.
func BumpPtr(p *int) { *p++ }
// Fresh returns a pointer to a new zero Counter (new is just &T{}).
func Fresh() *Counter { return new(Counter) }
// Describe prints the nil-ness of a pointer without dereferencing it.
func Describe(c *Counter) string {
if c == nil {
return "nil counter"
}
return fmt.Sprintf("counter %d", c.N)
}
// SafeRead dereferences p and converts the runtime panic into an error.
func SafeRead(p *Counter) (n int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return p.N, nil
}$ go test ./basics
ok academy/pointers/basicsNo pointer arithmetic Must-know
In plain words: you cannot write p + 1 or p++ to walk through memory. To visit elements, index a slice or array; the runtime checks the bounds.
Common misunderstanding: "Then Go cannot do low-level work." It can, through unsafe (unsafe), but that is opt-in, loudly named and outside the compatibility promise.
Definition: the spec defines no arithmetic operators on pointer types. A pointer can be converted only to unsafe.Pointer and then to uintptr through the unsafe package.
| Task in C | Go idiom |
|---|---|
for (p = a; p < end; p++) | for i := range a or for _, v := range a |
p[i] on a raw buffer | s[i], bounds-checked |
| Skip a header | s[n:] |
| Reinterpret bytes | encoding/binary, or unsafe as the last resort |
1 s := []int{1, 2, 3}
2 _ = s[3]
// panic: runtime error: index out of range [3] with length 3Real scenario: a parser that in C would advance a char * becomes an index into []byte; an overrun becomes a panic instead of memory corruption.
Nil pointers and the dereference panic Must-know
In plain words: a nil pointer points nowhere. Using it as if it pointed somewhere crashes the goroutine with a message that names the problem.
Common misunderstanding: "recover makes nil panics harmless." It makes them survivable, not correct; the bug (an unchecked error or an unset field) is still there. Also var p *T; p.Method() does not panic if Method has a pointer receiver that never touches *p.
Definition: dereferencing nil raises a run-time panic of type runtime.Error. On Linux and macOS it arrives as SIGSEGV (address 0) that the runtime converts into the panic.
$ go run nilmain.go # var p *T; println(p.N)
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x10037857c]
goroutine 1 [running]:
main.main()
.../nilmain.go:7 +0x1c
exit status 2The text is real output from Go 1.27.4 on macOS (the code= and pc= values differ per OS and run). Where nil comes from most often:
| Source | Example | Defence |
|---|---|---|
| Ignored error | f, _ := os.Open(n); f.Read(b) | Check err before use |
| Map miss with pointer values | m["x"].Field | v, ok := m["x"] |
| Unset struct field | s.logger.Info(...) | Constructor sets it; validate in New |
| Interface holding a typed nil | var e *MyErr; var err error = e then err != nil is true | Return a literal nil, see errors |
| Optional JSON field | *req.Name when absent | if req.Name != nil |
Real scenario: an HTTP handler where user, _ := repo.Find(id) returns nil, ErrNotFound and the next line reads user.Email: the net/http server recovers the panic per request and logs http: panic serving, but the client gets a closed connection.
Fix: guard at the boundary and make nil meaningful. A method may document that a nil receiver is valid and handle it (as Describe does in the snippet).
Pointer and value receivers Must-know
In plain words: a value receiver works on a copy of the struct; a pointer receiver works on the original. If a method must change the struct, or the struct is large, use a pointer receiver.
Common misunderstanding: "A method on a value type can still mutate the struct because Go passes objects by reference." No object is passed by reference; the receiver is an ordinary parameter and is copied.
Definition: a method with receiver (c Counter) receives a copy. A method with (c *Counter) receives the address. A variable c that is addressable can call a pointer method (c.IncPtr() becomes (&c).IncPtr()); a map element or a function result cannot. The method set of T has only value-receiver methods; the method set of *T has both, which decides interface satisfaction. This page gives the memory view; the full rules and the "do not mix receivers" guidance are in Structs, Methods, Constructors, Embedding & Struct Tags.
T1 (value receiver) T2 (pointer receiver)
1 c := Counter{N: 0} 1 c := Counter{N: 0}
2 c.IncValue() // copy: N++ on copy 2 c.IncPtr() // (&c).IncPtr()
3 fmt.Println(c.N) // 0 3 fmt.Println(c.N) // 1| Receiver | Copies the struct | Can mutate | In method set of T | In method set of *T | Typical use |
|---|---|---|---|---|---|
(c Counter) | yes | no (copy only) | yes | yes | small immutable values (time.Time) |
(c *Counter) | no | yes | no | yes | stateful types, large structs, types with sync.Mutex |
The Go code-review wiki gives the practical rules: if the receiver is a struct containing a sync.Mutex or similar field, it must be a pointer to avoid copying; if it is a large struct, a pointer is cheaper; when in doubt, use a pointer. The same snippet has the tests (TestReceivers).
When to use a pointer, and when not to Must-know
In plain words: use a pointer when sharing or absence is the point; otherwise pass the value. Do not reach for a pointer just because the struct has many fields.
Common misunderstanding: "Pointers are always cheaper than copies." Copying 3 words is as cheap as passing a pointer, and a pointer can move the object to the heap, add GC scanning and add a cache miss on every access.
| Situation | Use | Reason |
|---|---|---|
| The callee must change the caller's data | pointer | mutation |
Type holds a sync.Mutex, sync.WaitGroup, atomic fields | pointer, never copy | go vet copylocks |
| Struct is hundreds of bytes and passed hot | pointer (measure first) | copy cost |
| Field may be absent (PATCH body, nullable column) | *T | nil is "not set" |
| Object identity matters (graph node, cache entry, registry) | pointer | two holders, one object |
Small plain value (int, time.Time, small struct) | value | cheaper, no escape |
| Slice, map, channel, func | value | already reference-like |
| Interface value | value | already holds a pointer inside |
| Pointer to an interface | almost never | confuses method sets |
1 func (s *Store) Add(it Item) // value: Item is 3 words, copied cheaply
2 func (s *Store) Find(id int) *Item // pointer: nil means not found
3 func Load(path string, cfg *Config) error // out-parameterReal scenario: a Config struct with 12 strings loaded once at startup and read-only everywhere: pass *Config to avoid 12 copies per call, or an immutable value held in an atomic.Pointer (Atomic pointers) when it reloads.
Slices, maps and channels are reference-like Important
In plain words: a map, a channel and a function value each contain a pointer to something shared; a slice is a small struct of pointer, length and capacity. Copying one of them copies the handle, not the data.
Common misunderstanding: "A slice passed by value is isolated from the caller." Writes to its elements are visible; only append growth that reallocates, or reslicing, is local.
slice header (3 words) backing array (shared)
┌─────┬─────┬─────┐ ┌───┬───┬───┬───┐
│ ptr │ len │ cap │ ───────────▶ │ 1 │ 2 │ 3 │ │
└─────┴─────┴─────┘ └───┴───┴───┴───┘| Type | What a copy shares | When you need * |
|---|---|---|
map[K]V | the hash table | never (a nil map reads fine, writing panics) |
chan T | the channel | never |
[]T | the backing array | *[]T only to let a callee change len or cap of the caller's slice |
func | the closure's captured variables | never |
interface | the dynamic value (often a pointer) | almost never |
[N]T array | nothing (value type, copied entirely) | for large arrays |
Slices of pointers versus pointers to slices. []*T is a slice whose elements are addresses: the objects can be shared and mutated through the slice, but each is a separate allocation and the GC has more to scan. []T stores values contiguously: better locality, but taking &s[i] and then appending can leave the pointer aimed at the old array. *[]T is only for an out-parameter that grows a slice; usually return the new slice instead (s = add(s, x)). Details of aliasing are in Arrays, Slices & Maps.
Pointer to a loop variable (Go 1.22) Important
In plain words: before Go 1.22, for _, v := range xs { ptrs = append(ptrs, &v) } stored the same address N times. Since 1.22 each iteration has its own v.
Common misunderstanding: "Fixed in every Go version." The new semantics apply per module, by the go directive in go.mod: a module that says go 1.21 keeps the old behaviour.
Definition: the Go 1.22 release notes say loop variables are "created anew for each iteration"; the 3-clause form for i := 0; ... also gets a fresh i per iteration, copied forward before the post statement.
1 items := []int{1, 2, 3}
2 for _, v := range items { ps = append(ps, &v) }
// go 1.21 module: *ps[0], *ps[1], *ps[2] = 3 3 3
// go 1.22 module: 1 2 3// Package loopvar shows pointers to loop variables under Go 1.22+ semantics.
package loopvar
// PointersToItems collects &v for each element. Since Go 1.22 every
// iteration has its own v, so the pointers are distinct.
func PointersToItems(items []int) []*int {
var out []*int
for _, v := range items {
out = append(out, &v)
}
return out
}
// PointersToElements points into the slice itself: mutation is visible there.
func PointersToElements(items []int) []*int {
out := make([]*int, 0, len(items))
for i := range items {
out = append(out, &items[i])
}
return out
}Note the second function: &items[i] points into the slice itself, so mutation is visible there; &v points at a per-iteration copy.
Optional fields: *string, *bool and JSON Must-know
In plain words: a plain string cannot say "not provided"; its zero value "" is also a legal answer. *string can: nil means absent, a pointer to "" means "set to empty".
Common misunderstanding: "omitempty on a string does the same." It drops both absent and empty, so you can never send a request that clears a field.
| Wire JSON | Name string | Name *string |
|---|---|---|
{} | "" | nil |
{"name":""} | "" | pointer to "" |
{"name":null} | "" (left as is) | nil |
{"name":"ada"} | "ada" | pointer to "ada" |
// Package optional uses *string to tell "absent" from "empty" in JSON.
package optional
import "encoding/json"
// PatchUser is a PATCH body: nil means "do not change".
type PatchUser struct {
Name *string `json:"name,omitempty"`
Bio *string `json:"bio,omitempty"`
Admin *bool `json:"admin,omitempty"`
}
// Ptr returns a pointer to v (Go 1.18+ generics; there is no &"literal").
func Ptr[T any](v T) *T { return &v }
// Apply returns the updated name and bio.
func Apply(name, bio string, p PatchUser) (string, string) {
if p.Name != nil {
name = *p.Name
}
if p.Bio != nil {
bio = *p.Bio // may be "" : an explicit clear
}
return name, bio
}
// Parse decodes a PATCH body.
func Parse(b []byte) (PatchUser, error) {
var p PatchUser
err := json.Unmarshal(b, &p)
return p, err
}Go has no &"literal", so a tiny generic Ptr[T any](v T) *T helper (as in the snippet) is common. The same pattern fits database/sql nullable columns (sql.NullString or *string with pgx) and PATCH endpoints; the encoder behaviour is in JSON, XML, Struct Tags, Encoder/Decoder, Base64.
Escape analysis: stack versus heap Must-know
In plain words: the compiler works out whether a variable can be thrown away when its function returns. If yes it lives on the goroutine stack (free to allocate and free); if something might still point to it later, it is "moved to heap".
Common misunderstanding: "I can control it with new versus &." You cannot; the FAQ says that from the correctness point of view you need not know. You only observe it with the compiler.
Definition: escape analysis is a static analysis in the compiler. A value escapes when its address is returned, stored in a heap object or a global, sent on a channel, captured by a closure that outlives the frame, converted to an interface in a way that cannot be proven local, or when its size is unknown at compile time or too large for the stack.
$ go build -gcflags=-m ./escape
escape/escape.go:9:6: can inline SumStack
escape/escape.go:16:6: can inline NewHeap
escape/escape.go:22:6: can inline NewValue
escape/escape.go:29:6: can inline ToInterface
escape/escape.go:17:2: moved to heap: p <- NewHeap returns &p
escape/escape.go:30:9: n escapes to heap <- stored in package-level interface(Real output, Go 1.27.4. SumStack and NewValue produce no escape line: they stay on the stack.)
| Pattern | Escapes? | Why |
|---|---|---|
p := Point{}; return p.X | no | nothing outlives the frame |
return &p | yes | address leaves the function |
sink = n with sink any | yes | boxed into a global |
fmt.Println(x) | usually yes | argument converted to any |
make([]int, n) with variable n | yes | size unknown at compile time |
make([]int, 10) not leaving | no | small constant size |
go func() { use(&x) }() | yes | goroutine outlives the frame |
Method value obj.Method stored in a field | yes | closure holds obj |
The test measures it rather than trusting the compiler output: testing.AllocsPerRun reports 0 allocations for the stack cases and at least 1 for NewHeap.
// Package escape has functions whose allocation behaviour is visible with
// go build -gcflags=-m.
package escape
// Point is a tiny value type.
type Point struct{ X, Y int }
// SumStack keeps p on the stack: nothing outlives the call.
func SumStack() int {
p := Point{1, 2}
q := &p
return q.X + q.Y
}
// NewHeap returns the address of a local, so the compiler moves it to the heap.
func NewHeap() *Point {
p := Point{1, 2}
return &p
}
// NewValue returns a copy: the struct is copied to the caller's stack frame.
func NewValue() Point {
return Point{1, 2}
}
var sink any
// ToInterface stores a value in a package-level interface: it escapes.
func ToInterface(n int) {
sink = n
}Real scenario: a hot path returns *Result per request; profiling shows millions of small heap objects. Returning Result by value (when it is small) removes the allocation and the GC work; the benchmark confirms it with -benchmem (allocs/op drops to 0). See Testing & Benchmarking.
The garbage collector Must-know
In plain words: you never free memory. A background collector finds objects no pointer can reach and reclaims them, while your goroutines keep running.
Common misunderstanding: "Garbage collection means unpredictable multi-second pauses." Go's collector is concurrent; stop-the-world phases are typically sub-millisecond. The real costs are CPU spent marking and memory held above the live heap.
Definition: Go uses a non-generational, concurrent, tri-color mark-and-sweep collector (the GC guide). Objects start white (not yet seen); roots (stacks, globals, registers) are scanned and referents become grey (queued); scanning a grey object turns it black and greys what it points to. When no grey objects remain, remaining white objects are unreachable and are swept. The collector is non-moving: addresses stay stable, which is why unsafe.Pointer to heap memory is meaningful.
A write barrier is a small piece of compiler-emitted code run on pointer writes while marking is active. It keeps the invariant that no black object points to a white one, so the mutator can keep working while the collector marks. The ISMM keynote explains that the barrier is on only during the GC.
1 sweep termination (stop-the-world, very short)
2 concurrent mark (write barrier ON; workers use up to 25% of CPU, mutator assists if it allocates too fast)
3 mark termination (stop-the-world, very short)
4 concurrent sweep (write barrier OFF)The two knobs. From the GC guide: the heap target is Live heap + (Live heap + GC roots) * GOGC / 100. GOGC (default 100) trades CPU for memory: 200 collects half as often and uses more memory; 50 the reverse. GOGC=off disables the proportional trigger. GOMEMLIMIT (Go 1.19, also debug.SetMemoryLimit) is a soft limit on the whole Go runtime's memory; the collector works harder as it nears it. A common container recipe is GOMEMLIMIT at about 90% of the container limit, with GOGC left at 100 or higher.
| Knob | Set by | Default | Effect | Risk |
|---|---|---|---|---|
GOGC | env or debug.SetGCPercent | 100 | heap may grow to double the live heap | higher = more memory |
GOMEMLIMIT | env or debug.SetMemoryLimit | unlimited | soft cap; GC runs more often near it | too low causes GC thrash |
GODEBUG=gctrace=1 | env | off | one line per cycle on stderr | verbose |
runtime.GC() | code | n/a | forces a cycle | tests only |
debug.FreeOSMemory() | code | n/a | GC and return memory to the OS | latency spike |
Real gctrace lines (Go 1.27.4, a loop allocating 64 KiB buffers):
gc 1 @0.021s 1%: 0.31+0.78+0.006 ms clock, 3.8+0.25/0.79/0+0.074 ms cpu, 3->4->1 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 12 P
gc 2 @0.026s 1%: 0.034+0.24+0.003 ms clock, ... 3->3->1 MB, 4 MB goal, ...Read it as: cycle number, time since start, share of CPU spent in GC, wall-clock stop-the-world sweep termination + concurrent mark + mark termination, heap size at start, at end and live (3->3->1 MB), and the goal. The test below proves the knob: with GOGC=10 the same workload ran 23 cycles, with GOGC=800 it ran none.
// Package gcknobs reads and sets GOGC and GOMEMLIMIT from code.
package gcknobs
import (
"runtime"
"runtime/debug"
)
// Snapshot is the part of runtime.MemStats worth printing.
type Snapshot struct {
HeapAlloc uint64
NumGC uint32
PauseNs uint64 // most recent stop-the-world pause
}
// Read returns a snapshot.
func Read() Snapshot {
var m runtime.MemStats
runtime.ReadMemStats(&m)
return Snapshot{HeapAlloc: m.HeapAlloc, NumGC: m.NumGC, PauseNs: m.PauseNs[(m.NumGC+255)%256]}
}
// Tune sets GOGC (percent) and the soft memory limit (bytes) and returns the
// previous values so the caller can restore them. percent < 0 disables the
// proportional trigger; limit < 0 only reads the current limit.
func Tune(percent int, limit int64) (oldPercent int, oldLimit int64) {
oldPercent = debug.SetGCPercent(percent)
oldLimit = debug.SetMemoryLimit(limit)
return
}Memory layout: padding, alignment, field order Important
In plain words: the CPU wants an int64 at an address divisible by 8. The compiler therefore inserts empty bytes (padding) between fields, and your struct can be bigger than the sum of its fields.
Common misunderstanding: "Field order is only style." Order changes size, and size changes cache behaviour and memory for slices of millions of elements.
Definition: unsafe.Alignof(x) is the alignment of x, unsafe.Offsetof(s.f) the byte offset of field f, and unsafe.Sizeof(x) the size of the value (not what it points to; a string header is 16 bytes, a slice header 24, a map or pointer 8 on 64-bit). Each field starts at a multiple of its alignment, and the struct size is a multiple of the largest field alignment.
| Type | Size (64-bit) | Alignment |
|---|---|---|
bool, int8, byte | 1 | 1 |
int16 | 2 | 2 |
int32, float32, rune | 4 | 4 |
int64, float64, pointer, map, chan, func | 8 | 8 |
string | 16 | 8 |
[]T | 24 | 8 |
interface | 16 | 8 |
Wasteful {A bool; B int64; C bool} Packed {B int64; A bool; C bool}
offset 0 A (1) offset 0 B (8)
offset 1-7 padding offset 8 A (1)
offset 8 B (8) offset 9 C (1)
offset 16 C (1) offset 10-15 padding
offset 17-23 padding size 16
size 24// Package layout shows struct padding and field ordering.
package layout
// Wasteful orders fields small, large, small: 7 bytes of padding twice.
type Wasteful struct {
A bool
B int64
C bool
}
// Packed orders fields large to small: padding only at the tail.
type Packed struct {
B int64
A bool
C bool
}
// Mixed shows alignment of different widths.
type Mixed struct {
A byte
B int32
C byte
D int16
E string
}With 10 million Wasteful values, reordering saves 80 MB. Do it only for types that exist in large numbers; the fieldalignment analyzer (from golang.org/x/tools) reports candidates. Put pointer-containing fields first when possible: the GC scans only up to the last pointer word of an object.
Atomic pointers: atomic.Pointer[T] Important
In plain words: when many goroutines read a configuration and one occasionally replaces it, you can publish the whole new object with one atomic pointer swap instead of locking every read.
Common misunderstanding: "An atomic pointer makes the pointed-to struct thread-safe." It only makes the pointer itself atomic. The struct must be treated as immutable once published; mutating it in place is still a data race.
Definition: sync/atomic has generic atomic.Pointer[T] (Go 1.19) with Load, Store, Swap and CompareAndSwap. Atomic operations are synchronizing: a Store happens before a Load that observes it, so everything written to the object before publication is visible to the reader.
T1 (writer) T2 (reader)
1 next := &Config{Version: 2}
2 h.cur.Store(next) -------------> 3 c := h.cur.Load() // sees Version 2 fully built// Package atomicptr swaps an immutable config snapshot without a lock.
package atomicptr
import "sync/atomic"
// Config is treated as immutable once published.
type Config struct {
Version int
Limit int
}
// Holder keeps the current snapshot.
type Holder struct{ cur atomic.Pointer[Config] }
// Load returns the current snapshot (nil before the first Store).
func (h *Holder) Load() *Config { return h.cur.Load() }
// Store publishes a new snapshot; readers see all of it or none of it.
func (h *Holder) Store(c *Config) { h.cur.Store(c) }
// Update retries a compare-and-swap loop until fn's result is installed.
func (h *Holder) Update(fn func(old Config) Config) {
for {
old := h.cur.Load()
var base Config
if old != nil {
base = *old
}
next := fn(base)
if h.cur.CompareAndSwap(old, &next) {
return
}
}
}| Approach | Reads | Writes | When |
|---|---|---|---|
sync.RWMutex around a struct | lock per read | lock per write | many fields updated together, rare reads |
atomic.Pointer[Config] + immutable snapshot | no lock | allocate, swap | read-heavy config, routing tables, feature flags |
atomic.Value | no lock | swap | same, pre-generics, no type safety |
| channel to an owner goroutine | message per read | message | one owner of mutable state |
The test runs 50 concurrent Update calls under go test -race, using the CAS loop to avoid lost updates. More primitives in sync & atomic.
unsafe.Pointer and uintptr Important
In plain words: unsafe.Pointer is the escape hatch that lets you reinterpret memory. uintptr is just a number that happens to be an address; the garbage collector does not know it refers to anything.
Common misunderstanding: "uintptr(unsafe.Pointer(p)) keeps p alive, so I can store it and convert back later." The unsafe source puts it plainly: "A uintptr is an integer, not a reference." The object may be freed (or the stack moved, since goroutine stacks can be copied) between the two conversions.
Definition: unsafe.Pointer can be converted to and from any pointer type and to and from uintptr. The unsafe package documents the valid patterns: (1) *T1 to *T2 with compatible layout, (2) Pointer to uintptr for printing only, (3) arithmetic in one expression: unsafe.Pointer(uintptr(p) + offset), now preferably unsafe.Add, (4) passing to syscall.Syscall in the call expression, (5) results of reflect.Value.Pointer or UnsafeAddr converted immediately, (6) reflect.SliceHeader/StringHeader (deprecated; use unsafe.Slice, unsafe.String, unsafe.StringData, unsafe.SliceData, Go 1.20).
BAD GOOD (single expression)
1 u := uintptr(unsafe.Pointer(p)) 1 q := (*int32)(unsafe.Add(unsafe.Pointer(p), 4))
2 // GC runs; p unreachable, memory reused
3 q := (*int32)(unsafe.Pointer(u + 4)) // GC sees the Pointer all the way
// dangling pointer: silent corruption// Package unsafeptr shows legitimate unsafe.Pointer uses and the uintptr trap.
package unsafeptr
import "unsafe"
// BytesView returns the bytes of s without copying (unsafe.StringData).
// The result must never be modified: string memory is read-only by contract.
func BytesView(s string) []byte {
if s == "" {
return nil
}
return unsafe.Slice(unsafe.StringData(s), len(s))
}
// StringView is the inverse: b must not change while the string is alive.
func StringView(b []byte) string {
if len(b) == 0 {
return ""
}
return unsafe.String(unsafe.SliceData(b), len(b))
}
// Pair has two int32 fields read through one 64-bit window.
type Pair struct{ Lo, Hi int32 }
// SecondField reaches Hi by pointer arithmetic, in ONE expression (valid
// pattern 3 from the unsafe docs).
func SecondField(p *Pair) int32 {
return *(*int32)(unsafe.Add(unsafe.Pointer(p), unsafe.Offsetof(p.Hi)))
}
// BrokenAddress is the classic bug: the address lives in a uintptr, which the
// GC does not treat as a reference, so the object may be freed or moved.
func BrokenAddress(p *Pair) uintptr {
return uintptr(unsafe.Pointer(p))
}| Use | Safe? | Note |
|---|---|---|
unsafe.String(ptr, n) over a byte slice you will not change | yes, with discipline | zero-copy; mutation breaks string immutability |
unsafe.Add to reach a field | yes | one expression, in bounds |
Store uintptr and convert later | no | go vet reports "possible misuse of unsafe.Pointer" |
Cast *[]byte to *string | not documented | use unsafe.String |
| Change a struct layout assumption | no | layout is not stable across versions |
go vet has an unsafeptr check for the bad conversions; the -d=checkptr instrumentation (on with -race) aborts on misaligned or out-of-bounds casts.
The Go memory model Must-know
In plain words: when one goroutine writes and another reads the same variable, nothing guarantees the reader sees the write unless you create an ordering between them with a channel, a mutex, a WaitGroup or an atomic.
Common misunderstanding: "A race on an int is harmless, at worst a stale value." The memory model says a program with a data race has no promise of sequential consistency; for multi-word values (strings, slices, interfaces) a torn read can produce a crash. The implementation may report the race and terminate.
Definition: a data race is "a write to a memory location happening concurrently with another read or write to that same location, unless all the accesses involved are atomic data accesses" (Go memory model). In the absence of data races, programs behave as if goroutines were interleaved on a single processor (DRF-SC). The ordering relation is happens-before: if event e1 happens before e2, e2 sees e1's writes.
| Edge that creates happens-before | Rule |
|---|---|
go statement | the statement happens before the new goroutine starts |
| Unbuffered channel | a receive happens before the matching send completes |
| Buffered channel | the k-th receive happens before the k+C-th send completes (C = capacity) |
| Channel send / close | send (or close) happens before the receive that sees it |
sync.Mutex | Unlock happens before the next Lock |
sync.Once | the return of f happens before any Do(f) returns |
sync/atomic | an atomic write happens before an atomic read that observes it |
sync.WaitGroup | Done happens before Wait returns |
T1 T2
1 data = 42
2 ready = true (plain) 3 for !ready {} // no happens-before
4 print(data) // may print 0, may never exit
FIX: ready is a channel close, or an atomic.Bool; then 1 happens before 4.The detector's report shape (from go test -race, expected text; not captured here):
WARNING: DATA RACE
Write at 0x00c000012345 by goroutine 8:
Previous read at 0x00c000012345 by goroutine 7:Everything about finding and fixing races is in Race Conditions, the Race Detector, Deadlocks, Concurrency vs Parallelism.
Cleanups: runtime.AddCleanup, finalizers and KeepAlive Good to know
In plain words: you can ask the runtime to call a function after an object becomes unreachable, as a safety net for an OS resource. It is a net, not a plan: you still close resources explicitly.
Common misunderstanding: "A finalizer will close my file at the right moment." Timing is unspecified; it may run late or never (for example at process exit). Finalizers also resurrect objects and delay their freeing.
Definition: runtime.SetFinalizer(obj, f) runs f(obj) once after obj is unreachable. Go 1.24 added runtime.AddCleanup(ptr, fn, arg): it is "more flexible, more efficient, and less error-prone", allows several cleanups per object, interior pointers, no leaks in cycles and does not delay freeing; "New code should prefer AddCleanup over SetFinalizer" (release notes). The cleanup argument must not reference ptr, or the object would never become unreachable. runtime.KeepAlive(x) marks x reachable up to that call, which protects code that hands out a raw handle (an fd or an unsafe address) while the Go wrapper could otherwise be collected mid-use.
1 h := Open(7) // AddCleanup(h, closeFn, 7)
2 use h.id // last use of h
3 (h unreachable) --> GC cycle --> closeFn(7) runs once, on a runtime goroutine// Package cleanup shows runtime.AddCleanup and runtime.KeepAlive.
package cleanup
import (
"runtime"
"sync/atomic"
)
// Handle owns an OS-level resource represented by an int id.
type Handle struct{ id int }
// Open attaches a cleanup that runs after the Handle becomes unreachable.
// The cleanup argument must not reference the Handle itself.
func Open(id int, closed *atomic.Int32) *Handle {
h := &Handle{id: id}
runtime.AddCleanup(h, func(id int) { closed.Add(1) }, id)
return h
}
// ID returns the resource id and keeps h alive until after the call.
func (h *Handle) ID() int {
v := h.id
runtime.KeepAlive(h)
return v
}The test forces collections with runtime.GC() and polls until the counter shows exactly one cleanup, which is the only reliable way to test it. Standard library users: os.File closes its descriptor this way as a last resort.
Profiling memory with pprof Important
In plain words: when memory is high or allocations are many, ask the runtime where they come from rather than guessing.
Common misunderstanding: "The heap profile shows everything that is using memory." It samples allocations (default every 512 KiB) and reflects the live heap as of the last completed GC; goroutine stacks, mmaped regions and cgo memory are not in it.
| Profile | Question it answers | How |
|---|---|---|
heap (inuse_space) | What is holding memory now? | go tool pprof http://localhost:6060/debug/pprof/heap |
heap (alloc_objects) | What allocates the most objects? | -sample_index=alloc_objects |
allocs | All allocations since start | /debug/pprof/allocs |
| benchmark | Allocations per operation | go test -bench . -benchmem -memprofile mem.out |
GODEBUG=gctrace=1 | GC frequency and heap sizes | stderr |
runtime/metrics, ReadMemStats | Counters in code | the gcknobs snippet |
import _ "net/http/pprof" // registers /debug/pprof/* on http.DefaultServeMux
// then: go tool pprof -top -sample_index=alloc_space http://localhost:6060/debug/pprof/heapNever expose /debug/pprof on a public listener. The overview of all tools is in the diagnostics guide and the pprof blog post.
Mechanics
Exact messages and what they mean Must-know
| Text | Cause | Fix |
|---|---|---|
panic: runtime error: invalid memory address or nil pointer dereference | *p or p.f on nil | check the pointer or the error that preceded |
panic: assignment to entry in nil map | write into a nil map | make(map...) |
panic: runtime error: index out of range [3] with length 3 | bad index | bounds check |
fatal error: all goroutines are asleep - deadlock! | every goroutine blocked | race-conditions-deadlocks |
WARNING: DATA RACE | unsynchronized access found by -race | add happens-before |
fatal error: unexpected signal during runtime execution | usually bad unsafe or cgo | audit unsafe |
fatal error: checkptr: pointer arithmetic result points to invalid allocation | unsafe arithmetic out of object (with -race or -d=checkptr) | stay in bounds |
go vet: possible misuse of unsafe.Pointer | uintptr converted back | single-expression pattern |
go vet: copylocks ... passes lock by value | struct with a mutex copied | pointer receiver or pointer param |
fatal error: out of memory | heap exhausted | find the leak, set GOMEMLIMIT |
Flags and environment you will use Must-know
| Setting | Meaning |
|---|---|
go build -gcflags=-m | print inlining and escape decisions; -m -m for reasons |
go build -gcflags=-S | assembly listing |
go test -race | race detector, also enables checkptr |
go test -bench . -benchmem | allocs/op and B/op |
GOGC=100, GOGC=off | collection frequency |
GOMEMLIMIT=900MiB | soft memory limit (suffixes B, KiB, MiB, GiB, TiB) |
GODEBUG=gctrace=1 | trace each cycle |
GOMAXPROCS | number of Ps; GC background workers target 25% of them |
Where values live Good to know
| Value | Typical home |
|---|---|
| Local that does not escape | goroutine stack (starts at a few KiB, grows by copying) |
Escaping local, new, &T{} that leaves | heap |
| Package-level variable | data or bss segment, a GC root |
| Map buckets, slice backing arrays, channel buffers | heap |
| Closure captured variable | heap if the closure escapes |
| Large local (over the compiler's limit) | heap |
Because stacks can be copied when they grow, a pointer into a stack is never stored in the heap; that rule is why uintptr addresses of locals are unsafe to keep.
Solving the classic problems
Problem: PATCH cannot clear a field
| Solution | How | Advantage | Cost |
|---|---|---|---|
*string fields | nil = absent | exact | extra helper to build values |
map[string]any | presence by key | flexible | no types |
| JSON merge patch library | RFC 7396 | standard | dependency |
Use the optional snippet above and test absent versus empty as the unit tests do.
Problem: a struct with a mutex was copied
1 type Cache struct { mu sync.Mutex; m map[string]int }
2 func (c Cache) Get(k string) int { c.mu.Lock(); ... } // copies the lock
// go vet: Get passes lock by value: Cache contains sync.MutexFix: pointer receiver (c *Cache); constructors return *Cache.
Problem: too many small allocations in a hot path
| Step | Tool |
|---|---|
| Measure | go test -bench . -benchmem |
| Find | -gcflags=-m, pprof alloc_objects |
| Return values, not pointers, for small types | code change |
| Pre-size slices and maps | make([]T, 0, n) |
| Reuse buffers | sync.Pool (sync & atomic) |
| Verify | benchmark allocs/op falls |
Problem: container killed by the OOM killer
| Cause | Fix |
|---|---|
| Heap grows past the cgroup limit between GC cycles | GOMEMLIMIT near 90% of the limit |
| Real leak (map never pruned, goroutine per request without exit) | heap profile diff, goroutine profile |
| Large transient buffers | stream with io.Reader, pool buffers |
Problem: a stale config in some goroutines
Use an immutable snapshot published through atomic.Pointer (see Atomic pointers); never mutate fields of the live object.
-- Where pointer-shaped optionality meets storage: a nullable column maps to *string / *time.Time
CREATE TABLE users (
id bigint PRIMARY KEY,
name text NOT NULL,
bio text NULL, -- NULL = never set (nil pointer); '' = cleared on purpose
deleted_at timestamptz NULL -- *time.Time in Go
);
-- A PATCH that sets bio to NULL versus '' must be distinguishable:
UPDATE users SET bio = $1 WHERE id = $2; -- $1 is *string: nil -> NULL, ptr to "" -> ''Choosing
| Situation | Choice | Extra technique | Reason |
|---|---|---|---|
| Small immutable data (point, money amount, time) | value | value receivers | no allocation, no aliasing |
| Type with identity or mutable state | pointer, *T constructor | pointer receivers throughout | one owner of state |
| Optional field in API or DB | *T | Ptr helper, tests for absent vs empty | nil carries meaning |
| Read-mostly shared config | atomic.Pointer[T] | immutable snapshots | lock-free reads |
| Memory above budget in a container | GOMEMLIMIT | pprof heap | soft limit with GC feedback |
| Millions of small structs | reorder fields | fieldalignment, slice of values | less padding, better locality |
| Need a zero-copy string/bytes view | unsafe.String, unsafe.Slice | never mutate | one copy saved, rules documented |
| Resource safety net | AddCleanup | explicit Close first | cleanup is not timely |
In architecture: from a single process to a distributed system
Monolith: one process, one database
All goroutines share one address space, so pointers are shared state. Rules: constructors return *T for stateful components (repository, cache, logger), request data travels as values or pointers owned by one goroutine, and anything shared is protected by a mutex or published as an immutable snapshot. Example: an HTTP handler decodes a request into a value, passes *Store for the shared store, and never retains a pointer into the request body after returning.
Modular monolith and multiple databases
Package boundaries are where pointer leaks hurt. Exporting *Order from the orders package lets any module mutate its internals; returning copies (or read-only views) keeps invariants inside. A module that returns []*Item from its cache hands out aliases into its own state. Prefer returning values or defensive copies at module boundaries and keep mutation behind methods.
Microservices
Pointers do not cross a process boundary: gRPC and JSON copy data, and nil on one side becomes an absent field, a default or null on the other. Optional semantics must be encoded explicitly: protobuf optional fields and wrapper types in proto3, *T with omitempty in JSON. A request PATCH /users/7 {"bio": null} flows API gateway to user service to database as nil to NULL; treating nil as empty string at any hop silently destroys data. Memory limits are per service: each Go service sets GOMEMLIMIT from its own container limit.
Distributed data: replicas, caches, NAT and containers
A pointer is meaningful only inside one process; identity across processes uses keys (IDs, versions). A local in-process cache holds pointers to shared objects; with several replicas each has its own copy, so invalidation needs an event, not a shared reference. Memory behaviour in orchestrators: Kubernetes memory limits kill the process (exit 137) when RSS passes the limit, which GOMEMLIMIT avoids by making the collector work harder first; CPU limits throttle the GC's background workers and raise tail latency.
Scaling path: 1x, 10x, 100x
| Load | Memory concern | Action |
|---|---|---|
| 1x | none visible | default GOGC, write clear code |
| 10x | allocation rate and GC CPU show in profiles | benchmark with -benchmem, pre-size, pool buffers, return small values |
| 100x | heap size, GC pauses and tail latency | GOMEMLIMIT plus higher GOGC, shard state per core or per instance, compact structs, avoid pointer-heavy maps (a map[string]*T of millions is expensive to scan), consider off-heap or external stores |
Lab
Everything here runs on the host with Go only. The outputs marked "real" were captured during authoring (Go 1.27.4, module go 1.24). Setup:
cd docs/snippets/go/pointers/go
gofmt -l . && go vet ./... && go test -race ./...- Nil panic. Save
type T struct{ N int }; func main() { var p *T; println(p.N) }asnilmain.goand rungo run nilmain.go. Real output:panic: runtime error: invalid memory address or nil pointer dereferencethen[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=...], exit status 2. - Escape analysis.
go build -gcflags=-m ./escape. Real output includesmoved to heap: pforNewHeapandn escapes to heapforToInterface, and nothing forSumStack. - Allocations measured.
go test -run TestAllocations -v ./escapepasses: 0 allocations for the stack cases. - Layout.
go test -run TestSizes -v ./layout: sizes 24 and 16 asserted. Try adding astringfield toPackedand predictSizeofbefore running. - GOGC.
go test -run TestGOGC -v ./gcknobs. Real output:cycles: GOGC=10 -> 23, GOGC=800 -> 0(counts vary by machine). - GC trace.
GODEBUG=gctrace=1 go run gc.goprintsgc 1 @0.021s 1%: ...lines as in the GC section. - Race (expected, not run). Remove the CAS loop from
Update, mutate*oldin place and rungo test -race ./atomicptr; expected:WARNING: DATA RACEwith two goroutine stacks, andFAIL. - pprof (expected, not run). Add
import _ "net/http/pprof"to a service, run load, thengo tool pprof -top http://localhost:6060/debug/pprof/heap; expected: a table sorted byflatbytes naming the allocating functions.
Common misconceptions
| Belief | Reality |
|---|---|
new allocates on the heap, &x on the stack | Escape analysis decides; both can be on the stack |
| Pointers are always faster than copying | Small copies are cheap; pointers can cause heap allocation and GC scanning |
| Go passes maps and slices by reference | Everything is passed by value; maps and slices are values that contain pointers |
| A pointer receiver is needed only to mutate | Also for large structs and types that must not be copied (mutexes) |
uintptr keeps an object alive | It is an integer; the GC ignores it |
| Garbage collection stops the program for a long time | Mark runs concurrently; stop-the-world phases are short |
Setting GOGC=off is a free speed-up | Memory then grows without bound unless GOMEMLIMIT is set |
defer or a finalizer frees memory at a known time | Memory is freed by the GC at an unspecified time |
A data race on an int is harmless | The memory model gives no guarantee for racy programs |
*string is slow, use "" for absent | "" cannot distinguish "not sent" from "clear it" |
for _, v := range always shares one variable | Not since Go 1.22 in modules declaring go 1.22 or later |
| A nil interface equals an interface holding a nil pointer | The latter is non-nil: it has a type |
Cheat sheet
| Topic | What to remember |
|---|---|
| Operators | &x address, *p dereference, new(T) zero value, no arithmetic |
| Nil | Zero value of pointers; dereference panics with invalid memory address or nil pointer dereference |
| Receivers | Pointer if mutating, large, or holding a lock; do not mix on one type |
| Optional | *T plus omitempty; nil = absent, pointer to zero = set |
| Reference-like | map, chan, func, interface, slice header are copied cheaply |
| Escape | go build -gcflags=-m; moved to heap is a fact, not a bug |
| Allocations | go test -bench . -benchmem, AllocsPerRun |
| GC | Concurrent tri-color mark and sweep, write barrier during mark |
GOGC | Default 100, heap target = live heap times (1 + GOGC/100) roughly |
GOMEMLIMIT | Soft limit, about 90% of the container memory |
| Layout | Order fields large to small; check with unsafe.Sizeof and Offsetof |
| Atomic pointer | Publish immutable snapshots with atomic.Pointer[T] |
unsafe | Single-expression patterns; never keep a uintptr |
| Memory model | No happens-before means no guarantee; use channels, mutexes, atomics |
| Cleanups | Prefer AddCleanup, always close explicitly, KeepAlive around raw handles |
| Profiling | pprof heap, -benchmem, gctrace |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does p2 := p copy when p is a *T? Must-know
Answer
Answer: The address only. Both pointers refer to the same variable.
2 — Why does var p *T; p.N panic but var p *T; p.Describe() may not? Must-know
Answer
Answer: Field access dereferences nil. A method with a pointer receiver that never dereferences it, or that checks for nil, runs fine.
3 — A function returns &local. Is that a bug? Must-know
Answer
Answer: No. Escape analysis moves the variable to the heap (moved to heap). It costs an allocation, nothing more.
4 — Name the two knobs that shape GC behaviour and their defaults. Important
Answer
Answer: GOGC (100) and GOMEMLIMIT (unlimited, a soft limit in bytes).
5 — What is a write barrier for? Important
Answer
Answer: While the collector marks concurrently, it greys the target of pointer stores so a black object never points to a white one that would then be freed wrongly.
6 — Why reorder struct fields from large to small? Important
Answer
Answer: To reduce padding: {bool; int64; bool} is 24 bytes, {int64; bool; bool} is 16.
7 — How do you represent "field not sent" versus "set to empty" in a JSON body? Must-know
Answer
Answer: Use *string (or *T): nil is absent, a pointer to the zero value is explicitly set.
8 — Why is uintptr(unsafe.Pointer(p)) stored in a variable dangerous? Important
Answer
Answer: A uintptr is an integer; the GC does not see a reference, so the object can be freed or moved, leaving a dangling address.
9 — What does the memory model say about a data race? Must-know
Answer
Answer: Only race-free programs get sequentially consistent behaviour; a race gives no such guarantee and the implementation may report and terminate.
10 — When does runtime.AddCleanup run, and what must its argument avoid? Good to know
Answer
Answer: After the object becomes unreachable, at an unspecified time; the argument must not reference the object itself.
11 — What does atomic.Pointer[T] make atomic? Important
Answer
Answer: Only the pointer swap. The pointed-to object must be immutable after publication.
Glossary
| Term | Meaning |
|---|---|
| pointer | A value holding the address of a variable, type *T |
& | Address-of operator |
* | Dereference operator, also the pointer type constructor |
new | Built-in allocating a zero value and returning its address |
| nil pointer dereference | Using a nil pointer's target; run-time panic |
| invalid memory address | Text of the nil dereference panic |
| pointer receiver | Method receiver (c *T); works on the original |
| value receiver | Method receiver (c T); works on a copy |
| escape analysis | Compiler pass deciding stack or heap placement |
| heap | Shared, garbage-collected memory |
| stack | Per-goroutine memory freed on return |
| garbage collector | Runtime component freeing unreachable heap objects |
| mark and sweep | Find reachable objects, then reclaim the rest |
| tri-color | White, grey, black marking scheme |
| write barrier | Code on pointer writes during marking that preserves the invariant |
| GC pause | Stop-the-world part of a cycle |
GOGC | Percentage controlling heap growth before the next cycle |
GOMEMLIMIT | Soft memory limit for the Go runtime |
| struct padding | Empty bytes inserted for alignment |
| alignment | Required address multiple for a type |
unsafe.Sizeof | Size of a value in bytes |
unsafe.Alignof | Alignment of a value |
unsafe.Offsetof | Byte offset of a struct field |
| field ordering | Arranging fields to minimise padding |
| optional field | A field that can be absent, modelled as *T |
atomic.Pointer | Generic atomic pointer type |
unsafe.Pointer | Pointer that converts to any pointer type |
uintptr | Integer big enough for an address; not a reference |
| memory model | Rules for when a read observes a write |
| happens-before | Ordering guaranteeing visibility |
| data race | Unsynchronized concurrent access with at least one write |
runtime.KeepAlive | Marks a value reachable until the call |
| finalizer | SetFinalizer function run after unreachability |
AddCleanup | Go 1.24 replacement for most finalizers |
| pprof | Profiling tool for CPU and memory |
| reference | A handle that shares underlying data |
| copy-on-write | PHP array strategy: copy only when modified |
| handle | An identifier for an object (PHP objects) |
For PHP/Laravel developers
PHP has three things that look like Go pointers, and none is identical.
| PHP | Go | Difference |
|---|---|---|
function f(array &$a), $b = &$a (reference) | *[]T, *T | Go requires & at the call site and * in the type; PHP references are symbols in a table |
| Objects are passed by handle | *T | A PHP object variable holds a handle; $b = $a shares the object. In Go, a struct is copied unless you use a pointer |
| Arrays are values with copy-on-write | slices share, arrays copy | PHP copies lazily on write; Go copies an array immediately and a slice header only |
| Memory freed by refcount plus cycle collector | tracing concurrent GC | Go has no destructor ordering; use defer Close() |
$a = [1, 2, 3];
$b = $a; // copy-on-write: no copy yet
$b[] = 4; // now $b is copied; $a is still [1, 2, 3]
$o = new Order(); $p = $o; $p->total = 10; // $o->total is 10 too: shared handleIn Go the equivalents are: b := a for an array copies at once; for a slice it shares the backing array (a surprise to PHP developers); p := o with o a struct copies, with o a *Order shares. The Laravel habit of "everything object-like is shared" maps to pointer types; the habit of "arrays are values" maps to Go arrays, not slices. PHP-FPM frees all memory at request end, so leaks rarely matter; a Go service lives for days, so a leaked map entry matters.
References
- The Go Programming Language Specification: address operators, pointer types, zero values, method sets (read for Go 1.25)
- Effective Go: allocation with
newandmake - Go FAQ: no pointer arithmetic, methods on values or pointers, heap versus stack
- The Go Memory Model: happens-before and data races
- A Guide to the Go Garbage Collector:
GOGC,GOMEMLIMIT - Getting to Go: The Journey of Go's Garbage Collector: tri-color, write barrier
- Go 1.5 GC announcement: concurrent collector introduction
- Go 1.22 release notes: per-iteration loop variables
- Go 1.24 release notes:
runtime.AddCleanup - Go 1.25 release notes
- Preview: Go 1.22 loop variable change
- Go Code Review Comments: receiver type
- Diagnostics and Profiling Go Programs
- Data Race Detector
- unsafe package source (Go 1.25): valid
unsafe.Pointerpatterns (pkg.go.dev returned 403 to the fetcher, so the package source was read instead) - sync/atomic Pointer source (Go 1.25)
- runtime finalizer and KeepAlive source (Go 1.25)