Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has pointers but no arithmeticWhy it exists
Spec, FAQ, memory model, GC historyWhere it comes from
&, *, new, zero value nilPointer basics
panic: runtime error: invalid memory addressNil pointers
Copy versus share, receiversPointer and value receivers
Mutation, big structs, optional, identityWhen to use a pointer
Slices, maps, channels are already referencesReference-like types
&v in a for loopPointer to a loop variable
*string and JSONOptional fields
Stack versus heap, moved to heapEscape analysis
GOGC, GOMEMLIMIT, write barrier, pausesThe garbage collector
Padding, unsafe.Sizeof, field orderMemory layout
atomic.Pointer[T]Atomic pointers
unsafe.Pointer and uintptrunsafe
Happens-before, data racesThe memory model
Finalizers, AddCleanup, KeepAliveCleanups
pprof heap and allocation profilesProfiling memory
PHP references, handles, copy-on-writeFor PHP/Laravel developers
Reproduce the outputsLab

Everything in one minute ​

The operators.

SyntaxIn plain wordsExampleResult
&xAddress of the variable xp := &xp has type *int
*pThe value p points to (dereference)*p = 4x becomes 4
*TType: pointer to Tvar p *intzero value is nil
new(T)Allocate a zero T, return its addressp := new(int)same as &T{} for structs
p.fField through a pointer (auto-dereference)c.Nsame as (*c).N
p == nilPointer points nowhereif c == nilsafe, no panic
p + 1Does not existcompile errorno pointer arithmetic

The decisions.

QuestionValuePointer
Must the callee change the caller's variable?noyes
Is the struct large or contains a mutex?small, copyablelarge, 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?noyes (identity)
Is it a map, slice, channel, func or interface?pass by valuerarely a pointer

The memory facts.

FactDetail
Stack versus heapThe compiler chooses by escape analysis, not by new versus &
CollectorConcurrent, non-generational, non-moving, tri-color mark and sweep
Main knobsGOGC (default 100) and GOMEMLIMIT (default off)
Struct sizeSum of fields plus padding; order fields large to small
Data raceUndefined-ish: the memory model only promises behaviour for race-free programs
uintptrAn 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, simplerStronger, richer
Value semantics: copy on assignment, no aliasingPointer semantics: one object, many holders
No pointer arithmetic: no buffer overruns through index mathsunsafe available, but fenced off and named
Garbage collection: no free, no use-after-freeYou 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 ​

  1. "new allocates on the heap and &x on 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.
  2. "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.
  3. "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 (append result) 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 false

Real 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.

FormMeaningNote
&xAddress of an addressable variableNot of map elements or function results
&T{...}Address of a fresh composite literalThe usual constructor form
new(T)Pointer to a zero TRare; &T{} is clearer
*pDereferencePanics if nil
p.f, p.M()Auto-dereference for fields and methodsNo -> 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.

go
// 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/basics

No 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 CGo idiom
for (p = a; p < end; p++)for i := range a or for _, v := range a
p[i] on a raw buffers[i], bounds-checked
Skip a headers[n:]
Reinterpret bytesencoding/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 3

Real 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 2

The 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:

SourceExampleDefence
Ignored errorf, _ := os.Open(n); f.Read(b)Check err before use
Map miss with pointer valuesm["x"].Fieldv, ok := m["x"]
Unset struct fields.logger.Info(...)Constructor sets it; validate in New
Interface holding a typed nilvar e *MyErr; var err error = e then err != nil is trueReturn a literal nil, see errors
Optional JSON field*req.Name when absentif 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
ReceiverCopies the structCan mutateIn method set of TIn method set of *TTypical use
(c Counter)yesno (copy only)yesyessmall immutable values (time.Time)
(c *Counter)noyesnoyesstateful 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.

SituationUseReason
The callee must change the caller's datapointermutation
Type holds a sync.Mutex, sync.WaitGroup, atomic fieldspointer, never copygo vet copylocks
Struct is hundreds of bytes and passed hotpointer (measure first)copy cost
Field may be absent (PATCH body, nullable column)*Tnil is "not set"
Object identity matters (graph node, cache entry, registry)pointertwo holders, one object
Small plain value (int, time.Time, small struct)valuecheaper, no escape
Slice, map, channel, funcvaluealready reference-like
Interface valuevaluealready holds a pointer inside
Pointer to an interfacealmost neverconfuses 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-parameter

Real 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 │   │
└─────┴─────┴─────┘              └───┴───┴───┴───┘
TypeWhat a copy sharesWhen you need *
map[K]Vthe hash tablenever (a nil map reads fine, writing panics)
chan Tthe channelnever
[]Tthe backing array*[]T only to let a callee change len or cap of the caller's slice
functhe closure's captured variablesnever
interfacethe dynamic value (often a pointer)almost never
[N]T arraynothing (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
go
// 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 JSONName stringName *string
{}""nil
{"name":""}""pointer to ""
{"name":null}"" (left as is)nil
{"name":"ada"}"ada"pointer to "ada"
go
// 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.)

PatternEscapes?Why
p := Point{}; return p.Xnonothing outlives the frame
return &pyesaddress leaves the function
sink = n with sink anyyesboxed into a global
fmt.Println(x)usually yesargument converted to any
make([]int, n) with variable nyessize unknown at compile time
make([]int, 10) not leavingnosmall constant size
go func() { use(&x) }()yesgoroutine outlives the frame
Method value obj.Method stored in a fieldyesclosure 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.

go
// 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
}
Goroutine stack (per call frame)frame of mainq := NewHeap() (8-byte pointer)frame of SumStackp := Point{1,2} (freed on return)no GC work: pop = freeHeap (shared, garbage collected)moved to heap: pPoint{1,2}freed only after the GCfinds no pointer to itreturned &p

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)
rootsABCDblack: scannedgrey: queuedwhite: not reached yetCycle: sweep termination, concurrent mark, mark termination, sweepInvariant: no black object points to a white oneWrite barrier (on only while marking) greys the target of every pointer storeAt the end, white objects are garbage and are swept; stop-the-world phases are short

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.

KnobSet byDefaultEffectRisk
GOGCenv or debug.SetGCPercent100heap may grow to double the live heaphigher = more memory
GOMEMLIMITenv or debug.SetMemoryLimitunlimitedsoft cap; GC runs more often near ittoo low causes GC thrash
GODEBUG=gctrace=1envoffone line per cycle on stderrverbose
runtime.GC()coden/aforces a cycletests only
debug.FreeOSMemory()coden/aGC and return memory to the OSlatency 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.

go
// 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.

TypeSize (64-bit)Alignment
bool, int8, byte11
int1622
int32, float32, rune44
int64, float64, pointer, map, chan, func88
string168
[]T248
interface168
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
go
// 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
}
Wasteful {A bool; B int64; C bool} = 24 bytesA7 bytes paddingB int64 (offset 8)C7 padPacked {B int64; A bool; C bool} = 16 bytesB int64 (offset 0)AC6 bytes tail paddingEach field starts at a multiple of its alignment; the struct size is a multiple of its largest alignment.

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
go
// 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
		}
	}
}
ApproachReadsWritesWhen
sync.RWMutex around a structlock per readlock per writemany fields updated together, rare reads
atomic.Pointer[Config] + immutable snapshotno lockallocate, swapread-heavy config, routing tables, feature flags
atomic.Valueno lockswapsame, pre-generics, no type safety
channel to an owner goroutinemessage per readmessageone 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
go
// 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))
}
UseSafe?Note
unsafe.String(ptr, n) over a byte slice you will not changeyes, with disciplinezero-copy; mutation breaks string immutability
unsafe.Add to reach a fieldyesone expression, in bounds
Store uintptr and convert laternogo vet reports "possible misuse of unsafe.Pointer"
Cast *[]byte to *stringnot documenteduse unsafe.String
Change a struct layout assumptionnolayout 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-beforeRule
go statementthe statement happens before the new goroutine starts
Unbuffered channela receive happens before the matching send completes
Buffered channelthe k-th receive happens before the k+C-th send completes (C = capacity)
Channel send / closesend (or close) happens before the receive that sees it
sync.MutexUnlock happens before the next Lock
sync.Oncethe return of f happens before any Do(f) returns
sync/atomican atomic write happens before an atomic read that observes it
sync.WaitGroupDone 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
go
// 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.

ProfileQuestion it answersHow
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
allocsAll allocations since start/debug/pprof/allocs
benchmarkAllocations per operationgo test -bench . -benchmem -memprofile mem.out
GODEBUG=gctrace=1GC frequency and heap sizesstderr
runtime/metrics, ReadMemStatsCounters in codethe 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/heap

Never 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 ​

TextCauseFix
panic: runtime error: invalid memory address or nil pointer dereference*p or p.f on nilcheck the pointer or the error that preceded
panic: assignment to entry in nil mapwrite into a nil mapmake(map...)
panic: runtime error: index out of range [3] with length 3bad indexbounds check
fatal error: all goroutines are asleep - deadlock!every goroutine blockedrace-conditions-deadlocks
WARNING: DATA RACEunsynchronized access found by -raceadd happens-before
fatal error: unexpected signal during runtime executionusually bad unsafe or cgoaudit unsafe
fatal error: checkptr: pointer arithmetic result points to invalid allocationunsafe arithmetic out of object (with -race or -d=checkptr)stay in bounds
go vet: possible misuse of unsafe.Pointeruintptr converted backsingle-expression pattern
go vet: copylocks ... passes lock by valuestruct with a mutex copiedpointer receiver or pointer param
fatal error: out of memoryheap exhaustedfind the leak, set GOMEMLIMIT

Flags and environment you will use Must-know ​

SettingMeaning
go build -gcflags=-mprint inlining and escape decisions; -m -m for reasons
go build -gcflags=-Sassembly listing
go test -racerace detector, also enables checkptr
go test -bench . -benchmemallocs/op and B/op
GOGC=100, GOGC=offcollection frequency
GOMEMLIMIT=900MiBsoft memory limit (suffixes B, KiB, MiB, GiB, TiB)
GODEBUG=gctrace=1trace each cycle
GOMAXPROCSnumber of Ps; GC background workers target 25% of them

Where values live Good to know ​

ValueTypical home
Local that does not escapegoroutine stack (starts at a few KiB, grows by copying)
Escaping local, new, &T{} that leavesheap
Package-level variabledata or bss segment, a GC root
Map buckets, slice backing arrays, channel buffersheap
Closure captured variableheap 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 ​

SolutionHowAdvantageCost
*string fieldsnil = absentexactextra helper to build values
map[string]anypresence by keyflexibleno types
JSON merge patch libraryRFC 7396standarddependency

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.Mutex

Fix: pointer receiver (c *Cache); constructors return *Cache.

Problem: too many small allocations in a hot path ​

StepTool
Measurego test -bench . -benchmem
Find-gcflags=-m, pprof alloc_objects
Return values, not pointers, for small typescode change
Pre-size slices and mapsmake([]T, 0, n)
Reuse bufferssync.Pool (sync & atomic)
Verifybenchmark allocs/op falls

Problem: container killed by the OOM killer ​

CauseFix
Heap grows past the cgroup limit between GC cyclesGOMEMLIMIT near 90% of the limit
Real leak (map never pruned, goroutine per request without exit)heap profile diff, goroutine profile
Large transient buffersstream 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.

sql
-- 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 ​

SituationChoiceExtra techniqueReason
Small immutable data (point, money amount, time)valuevalue receiversno allocation, no aliasing
Type with identity or mutable statepointer, *T constructorpointer receivers throughoutone owner of state
Optional field in API or DB*TPtr helper, tests for absent vs emptynil carries meaning
Read-mostly shared configatomic.Pointer[T]immutable snapshotslock-free reads
Memory above budget in a containerGOMEMLIMITpprof heapsoft limit with GC feedback
Millions of small structsreorder fieldsfieldalignment, slice of valuesless padding, better locality
Need a zero-copy string/bytes viewunsafe.String, unsafe.Slicenever mutateone copy saved, rules documented
Resource safety netAddCleanupexplicit Close firstcleanup 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 ​

LoadMemory concernAction
1xnone visibledefault GOGC, write clear code
10xallocation rate and GC CPU show in profilesbenchmark with -benchmem, pre-size, pool buffers, return small values
100xheap size, GC pauses and tail latencyGOMEMLIMIT 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:

bash
cd docs/snippets/go/pointers/go
gofmt -l . && go vet ./... && go test -race ./...
  1. Nil panic. Save type T struct{ N int }; func main() { var p *T; println(p.N) } as nilmain.go and run go run nilmain.go. Real output: panic: runtime error: invalid memory address or nil pointer dereference then [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=...], exit status 2.
  2. Escape analysis. go build -gcflags=-m ./escape. Real output includes moved to heap: p for NewHeap and n escapes to heap for ToInterface, and nothing for SumStack.
  3. Allocations measured. go test -run TestAllocations -v ./escape passes: 0 allocations for the stack cases.
  4. Layout. go test -run TestSizes -v ./layout: sizes 24 and 16 asserted. Try adding a string field to Packed and predict Sizeof before running.
  5. GOGC. go test -run TestGOGC -v ./gcknobs. Real output: cycles: GOGC=10 -> 23, GOGC=800 -> 0 (counts vary by machine).
  6. GC trace. GODEBUG=gctrace=1 go run gc.go prints gc 1 @0.021s 1%: ... lines as in the GC section.
  7. Race (expected, not run). Remove the CAS loop from Update, mutate *old in place and run go test -race ./atomicptr; expected: WARNING: DATA RACE with two goroutine stacks, and FAIL.
  8. pprof (expected, not run). Add import _ "net/http/pprof" to a service, run load, then go tool pprof -top http://localhost:6060/debug/pprof/heap; expected: a table sorted by flat bytes naming the allocating functions.

Common misconceptions ​

BeliefReality
new allocates on the heap, &x on the stackEscape analysis decides; both can be on the stack
Pointers are always faster than copyingSmall copies are cheap; pointers can cause heap allocation and GC scanning
Go passes maps and slices by referenceEverything is passed by value; maps and slices are values that contain pointers
A pointer receiver is needed only to mutateAlso for large structs and types that must not be copied (mutexes)
uintptr keeps an object aliveIt is an integer; the GC ignores it
Garbage collection stops the program for a long timeMark runs concurrently; stop-the-world phases are short
Setting GOGC=off is a free speed-upMemory then grows without bound unless GOMEMLIMIT is set
defer or a finalizer frees memory at a known timeMemory is freed by the GC at an unspecified time
A data race on an int is harmlessThe 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 variableNot since Go 1.22 in modules declaring go 1.22 or later
A nil interface equals an interface holding a nil pointerThe latter is non-nil: it has a type

Cheat sheet ​

TopicWhat to remember
Operators&x address, *p dereference, new(T) zero value, no arithmetic
NilZero value of pointers; dereference panics with invalid memory address or nil pointer dereference
ReceiversPointer if mutating, large, or holding a lock; do not mix on one type
Optional*T plus omitempty; nil = absent, pointer to zero = set
Reference-likemap, chan, func, interface, slice header are copied cheaply
Escapego build -gcflags=-m; moved to heap is a fact, not a bug
Allocationsgo test -bench . -benchmem, AllocsPerRun
GCConcurrent tri-color mark and sweep, write barrier during mark
GOGCDefault 100, heap target = live heap times (1 + GOGC/100) roughly
GOMEMLIMITSoft limit, about 90% of the container memory
LayoutOrder fields large to small; check with unsafe.Sizeof and Offsetof
Atomic pointerPublish immutable snapshots with atomic.Pointer[T]
unsafeSingle-expression patterns; never keep a uintptr
Memory modelNo happens-before means no guarantee; use channels, mutexes, atomics
CleanupsPrefer AddCleanup, always close explicitly, KeepAlive around raw handles
Profilingpprof heap, -benchmem, gctrace

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
pointerA value holding the address of a variable, type *T
&Address-of operator
*Dereference operator, also the pointer type constructor
newBuilt-in allocating a zero value and returning its address
nil pointer dereferenceUsing a nil pointer's target; run-time panic
invalid memory addressText of the nil dereference panic
pointer receiverMethod receiver (c *T); works on the original
value receiverMethod receiver (c T); works on a copy
escape analysisCompiler pass deciding stack or heap placement
heapShared, garbage-collected memory
stackPer-goroutine memory freed on return
garbage collectorRuntime component freeing unreachable heap objects
mark and sweepFind reachable objects, then reclaim the rest
tri-colorWhite, grey, black marking scheme
write barrierCode on pointer writes during marking that preserves the invariant
GC pauseStop-the-world part of a cycle
GOGCPercentage controlling heap growth before the next cycle
GOMEMLIMITSoft memory limit for the Go runtime
struct paddingEmpty bytes inserted for alignment
alignmentRequired address multiple for a type
unsafe.SizeofSize of a value in bytes
unsafe.AlignofAlignment of a value
unsafe.OffsetofByte offset of a struct field
field orderingArranging fields to minimise padding
optional fieldA field that can be absent, modelled as *T
atomic.PointerGeneric atomic pointer type
unsafe.PointerPointer that converts to any pointer type
uintptrInteger big enough for an address; not a reference
memory modelRules for when a read observes a write
happens-beforeOrdering guaranteeing visibility
data raceUnsynchronized concurrent access with at least one write
runtime.KeepAliveMarks a value reachable until the call
finalizerSetFinalizer function run after unreachability
AddCleanupGo 1.24 replacement for most finalizers
pprofProfiling tool for CPU and memory
referenceA handle that shares underlying data
copy-on-writePHP array strategy: copy only when modified
handleAn identifier for an object (PHP objects)

For PHP/Laravel developers ​

PHP has three things that look like Go pointers, and none is identical.

PHPGoDifference
function f(array &$a), $b = &$a (reference)*[]T, *TGo requires & at the call site and * in the type; PHP references are symbols in a table
Objects are passed by handle*TA 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-writeslices share, arrays copyPHP copies lazily on write; Go copies an array immediately and a slice header only
Memory freed by refcount plus cycle collectortracing concurrent GCGo has no destructor ordering; use defer Close()
php
$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 handle

In 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 ​

Built by Morteza Negahi