Prove your Go code works: table-driven tests & subtests, helpers like t.Cleanup, t.Parallel and TestMain, mocks & fakes via interfaces, benchmarks with pprof, plus fuzzing and the race detector.
Imagine passing an array of 250,000 float64 sensor readings — roughly 2 MB — to a function, and then wondering why your memory profiler suddenly shows copies of that data everywhere. The reason is a core Go principle: an array is a value. Its type carries the fixed size ([4]int and [5]int are two completely different types), and every assignment copies the entire array.
A slice, on the other hand, is just a small reference to the array behind it — the so-called slice header. Assigning a slice copies only that header, not the data. That is why slices behave like references on element access, even though they are copied by value too.
The slice header
At runtime a slice is a small struct with three words: a pointer to the first element of the backing array, the length (len), and the capacity (cap). Because assignments copy only this header, two copies point at the same array — which is why a slice behaves like a reference while an array behaves like a value.
You can observe the difference in a few lines:
package main
import "fmt"
func main() {
// Array: a complete copy on assignment
a := [4]int{1, 2, 3, 4}
b := a
b[0] = 99
fmt.Println(a, b)
// → [1 2 3 4] [99 2 3 4]
// Slice: only the header is copied, the array stays shared
s := []int{1, 2, 3, 4}
t := s
t[0] = 99
fmt.Println(s, t)
// → [99 2 3 4] [99 2 3 4]
fmt.Println(len(s), cap(s))
// → 4 4
}
For a slice literal, len and cap start out equal. Things get interesting with reslicing: s[low:high] cuts a window out of the existing slice without copying a single byte. The new header points into the middle of the old array, len describes the window width, and cap describes the remaining space up to the end of the backing array.
s := make([]int, 3, 10) // len 3, cap 10
u := s[1:] // window starting at index 1
fmt.Println(len(s), cap(s))
// → 3 10
fmt.Println(len(u), cap(u))
// → 2 9 — cap drops by the cut-off position
tail := s[2:]
tail[0] = 42 // writes into the same array as s
fmt.Println(s)
// → [0 0 42]
This shared view is a feature, not a bug: reslicing makes function signatures like process(data []byte) extremely cheap because nothing is ever copied. The price is that you always have to keep in mind whose memory you are modifying.
⚠ Common mistake: Coming from JavaScript or Python, you might expect
b := awith an array to share data like an object — and wonder whyb[0] = 99leaves the original untouched. In Go an array is a value, and assignment copies every element. The reverse holds for slices: they share the same array on element access, even though their header was copied.
Check: You write b := a, where a is an array of type [4]int, and then set b[1] = 7. What does a contain?
Answer: a is unchanged, because b is a complete copy
Arrays are values in Go: assignment copies all four elements, after which two independent arrays exist. Only slices share the backing array, because only their small header is copied.
Takeaways:
len, and cap; assignment copies only the header.s[low:high]) copies no data — it just shifts the header's pointer.cap is the space up to the end of the backing array, not the window width.append is the most-used function around slices, which is exactly why it deserves a look under the hood. Every call must decide: is there enough capacity, or does a bigger array have to be allocated and everything copied over? That is not an academic detail — it determines whether two slices keep sharing the same memory or quietly drift apart.
The classic stumble from real projects: two code paths work on the same data through a reslice. One of them appends an element — and because capacity is still available, that element lands right in the middle of the other slice's data. No compiler error, no panic, just quietly corrupted data.
The growth strategy
When cap runs out, the runtime allocates a new, larger array and copies the old elements across. For small slices, Go typically doubles the capacity at each step (1, 2, 4, 8, 16 ...). If you know the target size, allocate with make([]T, 0, n) up front and save yourself the copy operations.
s := make([]int, 0)
prev := cap(s)
for i := 1; i <= 9; i++ {
s = append(s, i)
if cap(s) != prev {
fmt.Printf("len=%d cap=%d (new array)\n", len(s), cap(s))
prev = cap(s)
}
}
// → len=1 cap=1 (new array)
// → len=2 cap=2 (new array)
// → len=3 cap=4 (new array)
// → len=5 cap=8 (new array)
// → len=9 cap=16 (new array)
As long as cap is not exhausted, append writes into the existing array — possibly into data that another slice believes it owns. Only when capacity runs out does the enlarged slice get its own new array, while the old one stays untouched.
a := []int{1, 2, 3, 4, 5}
b := a[1:3] // len 2, shares the array with a
b = append(b, 99) // capacity remains: lands in a[3]
fmt.Println(a)
// → [1 2 3 99 5]
fmt.Println(b)
// → [2 3 99]
The way out is the full slice expression s[low:high:max], which deliberately caps the window's capacity:
a := []int{1, 2, 3, 4, 5}
b := a[1:3:3] // cap deliberately limited to 3
b = append(b, 99) // forces a new allocation
fmt.Println(a)
// → [1 2 3 4 5] — a stays untouched
fmt.Println(b)
// → [2 3 99]
And the copy trap: copy(dst, src) transfers only as many elements as fit into the smaller of the two slices — with an empty or nil destination that is exactly zero, without any error:
src := []int{1, 2, 3, 4, 5}
dst := make([]int, 3) // without make (dst := []int{}), n would be 0
n := copy(dst, src)
fmt.Println(n, dst)
// → 3 [1 2 3]
⚠ Common mistake: An
appendon a reslice can silently overwrite the neighboring slice's data as long as the shared array has spare capacity. If you hand out a window vias[low:high]and let the other side append, either use the full slice expressions[low:high:max]or make a real copy before appending.
Check: After s := make([]int, 3, 10), the code runs s = append(s, 42). Does this allocate a new backing array?
Answer: No, because the capacity of 10 is enough for 4 elements — the same array is reused
append only allocates when len equals cap. Here len is 3 and cap is 10, so the element is written into the existing array and only len in the header increases. Many people wrongly assume append always copies.
Takeaways:
append allocates a new array only when len equals cap; otherwise it writes into the existing one.make([]T, 0, n) avoids the copying.append with spare capacity can overwrite the neighboring slice's data.s[low:high:max] limits cap and forces a split on the next append.copy transfers min(len(dst), len(src)) elements — the destination must be big enough first.Maps in Go are reference semantics through and through: the assignment m2 := m1 does not copy a single entry — both variables point at the same hashmap in memory. And one central behavior regularly causes surprises: accessing a missing key does not panic; it silently returns the zero value of the value type.
A scenario from everyday work: a config map holds ports by service name, a typo in the key ("apiGateway" instead of api-gateway) goes unnoticed, and the program keeps running — with port 0. This is exactly what the comma-ok idiom is for, turning the existence check into a one-liner.
The comma-ok idiom
The two-value access v, ok := m[key] separates two cases Go otherwise cannot distinguish: the key is missing (ok == false, v is the zero value) or it exists and its value happens to be the zero value. Only with ok do you know for sure the entry was really there — delete, in contrast, never reports missing keys as errors.
m := map[string]int{"go": 2009, "rust": 2010}
year, ok := m["python"]
fmt.Println(year, ok)
// → 0 false
m["python"] = 1991
year, ok = m["python"]
fmt.Println(year, ok)
// → 1991 true
delete(m, "cobol") // key never existed — not an error
fmt.Println(len(m))
// → 3
for k := range m {
fmt.Println(k)
}
// → go, rust, python — order deliberately randomized
The builtin map is deliberately not safe for concurrent use: as soon as two goroutines write at the same time — or one writes while another reads — the runtime aborts with fatal error: concurrent map writes. That is not an ordinary panic: a recover in another goroutine cannot save you, the process is gone. The race detector (go test -race) reliably finds such spots before it happens.
The standard solution is a sync.Mutex around every access. For pure counter or cache workloads with heavy reads, sync.Map is also worth a look — but in most cases a mutex plus a normal map is the clearer choice.
var counter = make(map[string]int)
var mu sync.Mutex
func incr(worker string) {
for i := 0; i < 1000; i++ {
mu.Lock()
counter[worker]++
mu.Unlock()
}
}
func main() {
var wg sync.WaitGroup
for _, w := range []string{"a", "b", "c"} {
wg.Add(1)
go func(name string) {
defer wg.Done()
incr(name)
}(w)
}
wg.Wait()
fmt.Println(counter["a"], counter["b"], counter["c"])
// → 1000 1000 1000
}
Without the mutex this program would very likely die with fatal error: concurrent map writes — and not deterministically, but exactly when production load is highest.
⚠ Common mistake: Writing to a nil map — for instance
var m map[string]intfollowed directly bym["x"] = 1— triggers the panicassignment to entry in nil map. Reading from a nil map is perfectly legal and returns the zero value. Onlymake(map[string]int)or a literal makes the map writable.
Check: What happens in Go when you access a key that does not exist in the map?
Answer: The zero value of the value type is returned; with the comma-ok idiom you additionally get ok = false
Missing keys silently return the zero value of the value type (0 for int) and never abort. The myth that missing keys panic like a slice index out of range is persistent — only the comma-ok idiom separates the two cases.
Takeaways:
v, ok := m[key] separates "missing" from "is the zero value".delete on a missing key is not an error; range order over maps is deliberately randomized.fatal error.sync.Mutex; the race detector (go test -race) finds violations before production falls over.Every Go developer knows this debugging session: a function appends to its slice parameter, and the caller sees nothing. The explanation follows directly from Lesson 21: parameters are passed by value — for a slice, that means the header. The function receives a copy of pointer, len, and cap. Writing into the array within the existing length is visible to the caller. Extending the slice grows only its local copy of the header — and with a full array it even allocates a brand-new array only it knows about.
func zeroOut(s []int) {
for i := range s {
s[i] = 0
}
}
func extendBroken(s []int) {
s = append(s, 99) // changes only the local header
}
nums := []int{1, 2, 3}
zeroOut(nums)
fmt.Println(nums)
// → [0 0 0] — writing to existing elements is visible
extendBroken(nums)
fmt.Println(nums)
// → [0 0 0] — the appended element exists only locally
nums = append(nums, 99)
fmt.Println(nums)
// → [0 0 0 99]
With maps the effect is distributed differently: the parameter is also a small reference, and insertions are visible to the caller. Only a complete rebinding of the parameter stays invisible:
func register(m map[string]bool) {
m["guest"] = true // visible to the caller
m = map[string]bool{} // local rebinding
m["phantom"] = true // lands only in the local map
}
visitors := map[string]bool{"admin": true}
register(visitors)
fmt.Println(visitors)
// → map[admin:true guest:true]
The rule of thumb: mutating is visible, extending is not
Changes to existing elements of a slice parameter and new entries in a map parameter are visible to the caller, because both use the same memory. Anything that changes a slice's len (append, a resliced header) stays local — the idiomatic way out is to return the slice: assign s = append(s, x) from the return value.
A declared but uninitialized slice is nil — not a panic value, but a perfectly normal state. len, cap, range, and append all work fine on it. A nil map can be read (zero value) but not written. Where the difference really hurts is JSON serialization:
var nilSlice []int
empty := []int{}
fmt.Println(nilSlice == nil, empty == nil, len(nilSlice), len(empty))
// → true false 0 0
nilSlice = append(nilSlice, 1)
fmt.Println(nilSlice)
// → [1] — append to nil is the normal case
var nilMap map[string]int
fmt.Println(nilMap["x"])
// → 0 — reading from a nil map is allowed
// nilMap["x"] = 1 would be: panic: assignment to entry in nil map
type User struct {
Tags []string `json:"tags"`
}
b1, _ := json.Marshal(User{})
b2, _ := json.Marshal(User{Tags: []string{}})
fmt.Println(string(b1))
// → {"tags":null}
fmt.Println(string(b2))
// → {"tags":[]}
API consumers that expect array fields often break on null — so initialize slice fields in response structs consistently with []T{} instead of leaving them nil.
⚠ Common mistake: You expect an
appendinside a function to reach the caller because "slices are references after all". In reality only the local header was extended; the caller keeps its oldlen. The function must return the slice, and the caller must assign the result —s = append(s, ...)at the call site.
Check: When does a caller see an element that a function appended to its slice parameter?
Answer: Only if the function returns the slice and the caller assigns the result
The slice header is passed by value. An append increases len only in the local copy — regardless of whether a new array was allocated or the existing one was written to. The caller sees the element only when the function returns the changed header and the caller assigns it.
Takeaways:
return append(s, x) and assignment at the call site.len, range, and append work without a panic.null) and empty ([]) — prefer [] for APIs.Coming from Java (streams) or JavaScript (.filter().map()), you may initially miss functional helpers in Go. The idiomatic Go answer is refreshingly plain: an explicit for loop with range. It is readable, free of magic, and well optimized by the compiler. Since generics (Go 1.18) and the slices package (Go 1.21), recurring patterns can also be expressed as small, type-safe helpers — without the interface{} contortions of earlier years.
The rule of thumb from practice: a single filter or map as a generic helper is fine. Five-stage chained pipelines in the Java style only create unreadability in Go — three clear loops with well-named intermediate variables are more honest there.
Generics make the helpers type-safe
func Filter[T any](s []T, keep func(T) bool) []T keeps the element type without reflection or type assertions. Chained together, the helpers form a pipeline; Go evaluates every step as its own loop over its own result slice — there is no lazy evaluation like in Java streams.
func Filter[T any](s []T, keep func(T) bool) []T {
out := make([]T, 0, len(s))
for _, v := range s {
if keep(v) {
out = append(out, v)
}
}
return out
}
func Map[T, U any](s []T, f func(T) U) []U {
out := make([]U, 0, len(s))
for _, v := range s {
out = append(out, f(v))
}
return out
}
prices := []int{199, 45, 1200, 89}
under500 := Filter(prices, func(p int) bool { return p < 500 })
fmt.Println(under500)
// → [199 45 89]
labels := Map(under500, func(p int) string {
return fmt.Sprintf("%.2f EUR", float64(p)/100)
})
fmt.Println(labels)
// → [1.99 EUR 0.45 EUR 0.89 EUR]
Reduce follows the same pattern: an accumulator walked through line by line. The starting value is a deliberate choice — for an empty slice the result is exactly that starting value, never a panic:
func Reduce[T, U any](s []T, init U, combine func(U, T) U) U {
acc := init
for _, v := range s {
acc = combine(acc, v)
}
return acc
}
type Order struct {
Customer string
Amount float64
}
orders := []Order{
{"Ada", 120.50},
{"Lin", 79.99},
{"Grace", 45.00},
}
total := Reduce(orders, 0.0, func(acc float64, o Order) float64 {
return acc + o.Amount
})
fmt.Printf("Total: %.2f EUR\n", total)
// → Total: 245.49 EUR
Before writing your own helpers, check the slices package — sorting, searching, and comparing are already there:
import "slices"
names := []string{"kiwi", "apple", "banana"}
slices.Sort(names)
fmt.Println(names)
// → [apple banana kiwi]
idx, ok := slices.BinarySearch(names, "banana")
fmt.Println(idx, ok)
// → 1 true
And the trap that wants to be built into every filter or reduce implementation: range over a slice gives you only a copy of each element. Modifying the copy does not change the slice's data:
type Customer struct {
Name string
Spent float64
}
customers := []Customer{{"Ada", 0}, {"Lin", 0}}
for _, c := range customers {
c.Spent = 100 // changes only the loop's copy
}
fmt.Println(customers)
// → [{Ada 0} {Lin 0}]
for i := range customers {
customers[i].Spent = 100 // via the index: really changed
}
fmt.Println(customers)
// → [{Ada 100} {Lin 100}]
⚠ Common mistake: In
for _, v := range customers,vis a copy of the element — setting fields onvdoes not change the slice's data. To mutate elements, access them through the index (customers[i].Spent = 100) or work with a slice of pointers.
Check: You set v.Spent = 100 inside for _, v := range customers. What happens to the customers slice?
Answer: Nothing — v is a copy, the slice stays unchanged
range copies every slice element into the loop variable. Changes to v affect only that copy. The myth that v is a reference often comes from languages like Python or C# — in Go you need the index: customers[i].Spent = 100.
Takeaways:
for loop; generic Filter/Map/Reduce helpers replace it only where they are genuinely more readable.slices package (Go 1.21+) ships sorting and searching out of the box.range hands out copies: mutate elements via the index (s[i].Field = ...), not through the loop variable.Course navigation: ← Module 4 · All 20 modules · Module 6 →