DEV Community

Stanley Chege Thuita
Stanley Chege Thuita

Posted on Edited on

The Mental Model That Unlocks All of Go

The short version: One idea makes most of Go's surprises predictable: every value has an owner, and data flows in directions you can see. This post explains that model, then puts numbers on it. Every claim is measured on Go 1.26.5 with code you can run: what copying really costs, when a pointer moves data to the heap, why a map race kills your program even with recover, and when a channel is slower than a mutex.

You want to learn Go? Really learn it, not just copy-paste from Stack Overflow?

Forget syntax for a moment. There's one mental model that makes goroutines, channels, interfaces and error handling stop feeling strange:

Go is about ownership and flow.

Two words. This post shows what they mean, then measures them, because a mental model is only as good as the predictions it gets right.

Contents

  1. Why Go feels strange coming from other languages
  2. Ownership: values are copied unless you share them
  3. Measured: what a copy costs
  4. Measured: a pointer isn't free either
  5. Flow: data moves in directions you can see
  6. Interfaces: a box holding a copy
  7. Problem 1: a goroutine panicked and took the program down
  8. Problem 2: the map that can't be shared
  9. Measured: channel owner vs mutex
  10. Ownership in a real system
  11. Run everything yourself
  12. Quick reference

Why Go feels strange coming from other languages

If you came from Python, Java or JavaScript, you learned to think in:

  • objects and methods,
  • inheritance hierarchies,
  • shared mutable state,
  • exceptions flying up the call stack.

Go has methods but no inheritance, discourages shared mutable state, and has no exceptions. So you fight it. You copy a huge struct in a loop without noticing. A goroutine panics and the whole service dies. A map shared between goroutines crashes "randomly". You reach for a try that doesn't exist.

You're not bad at Go. You're using the wrong model.

Ownership: values are copied unless you share them

In Go, assignment and function calls copy values. Always. What differs is what the value is:

Type What a copy copies So after a copy...
int, struct, [N]T array All of the data Two independent values
Pointer *T The address Two names for one value
Slice, map, channel, function, interface A small header that refers to shared data Two names for the same underlying data
type User struct {
    Name string
    Age  int
}

func birthday(u User) { u.Age++ }      // changes a copy
func birthdayP(u *User) { u.Age++ }    // changes the caller's value

u := User{Name: "Alice", Age: 30}
birthday(u)   // u.Age is still 30
birthdayP(&u) // u.Age is now 31
Enter fullscreen mode Exit fullscreen mode

Rule 1: values are copied unless you explicitly share them. That one rule explains why for _, v := range items gives you copies, why methods that modify need pointer receivers, and why large structs are often passed by pointer.

Measured: what a copy costs

The usual claim is that passing a large struct by value is expensive. How expensive? A struct holding [1024]int is 8 KB. A benchmark calling a non-inlined function a few million times, once with the struct and once with a pointer to it:

type BigStruct struct{ Data [1024]int }

//go:noinline
func byValue(b BigStruct) int { return b.Data[0] + b.Data[1023] }

//go:noinline
func byPointer(b *BigStruct) int { return b.Data[0] + b.Data[1023] }
Enter fullscreen mode Exit fullscreen mode
cpu: Apple M1
BenchmarkByValue-8           5678077           192.6 ns/op         0 B/op          0 allocs/op
BenchmarkByPointer-8        567010612            2.123 ns/op           0 B/op          0 allocs/op
Enter fullscreen mode Exit fullscreen mode

About 90× slower by value: every call copies 8 KB onto the stack. Call it a million times and you've moved 8 GB of memory to read two integers.

But notice the scale: 192 ns is still fast. For a struct of a few fields, copying is cheaper than chasing a pointer. Pass small structs by value, large ones (rule of thumb: hundreds of bytes and up, or anything with a mutex inside) by pointer, and measure before "optimising" a small one.

Measured: a pointer isn't free either

Sharing via a pointer has its own cost, which the "always use pointers for performance" advice skips. A value whose address outlives its function must live on the heap, where the garbage collector has to track it. The compiler decides this with escape analysis, and it will tell you what it decided:

func newUserValue() User   { return User{Name: "Alice", Age: 30} }
func newUserPointer() *User { return &User{Name: "Alice", Age: 30} }
Enter fullscreen mode Exit fullscreen mode
go build -gcflags=-m .
Enter fullscreen mode Exit fullscreen mode
./main.go:10:38: &User{...} escapes to heap
./main.go:14:21: &User{...} does not escape
Enter fullscreen mode Exit fullscreen mode

Line 10 is newUserPointer itself: returning &User{...} means the value must outlive the function, so it escapes to the heap. Line 14 is the same call inlined into main, where the compiler can see the pointer never leaves main, so it stays on the stack after all.

Lessons:

  • Returning a pointer can cost a heap allocation and garbage-collector work; returning a small value usually doesn't.
  • Inlining changes the answer, so reason about hot paths with -gcflags=-m and a benchmark, not intuition.
  • 0 B/op in the benchmark above means no heap allocation per call. Watch that column; it's often where the real cost hides.

Flow: data moves in directions you can see

The second half of the model: in Go, data flows in explicit directions.

  • Functions: in through arguments, out through return values. No hidden outputs, no exceptions jumping frames.
  • Errors: returned as values, travelling up the call stack one return err at a time. You can see every place an error can leave a function.
  • Channels: from sender to receiver. A send can also be a transfer of ownership: after ch <- buf, the sender should stop touching buf.
  • Interfaces: behaviour flows from a concrete type into an abstraction. var w io.Writer = os.Stdout.
  • Context: cancellation flows down a tree of operations, never up.

Whenever you're confused by a Go program, ask three questions:

  1. Where does this data come from?
  2. Where is it going?
  3. Who owns it right now?

Most Go bugs are a wrong answer to question 3.

Interfaces: a box holding a copy

An interface value is a small pair: a pointer to the dynamic type, and the value (or a pointer to it). Two ownership consequences catch almost everyone once.

Storing a value in an interface copies it. After the copy, the interface and the original are independent:

type Counter struct{ n int }

func (c Counter) IncValue()    { c.n++ } // value receiver: works on a copy
func (c *Counter) IncPointer() { c.n++ } // pointer receiver: works on the original

c := Counter{}
c.IncValue()                // c.n is still 0
c.IncPointer()              // c.n is 1
var i any = c               // the interface holds a copy of c
c.IncPointer()              // c.n is 2, the copy still says 1
Enter fullscreen mode Exit fullscreen mode
2. after IncValue: 0
   after IncPointer: 1
   copy inside the interface: 1 | original: 2
Enter fullscreen mode Exit fullscreen mode

A nil pointer inside an interface is not a nil interface. This is the most famous Go gotcha, and it's an ownership question: the interface owns a type even when the pointer is nil.

type PaymentError struct{ Reason string }

func (e *PaymentError) Error() string { return e.Reason }

func pay(ok bool) error {
    var perr *PaymentError
    if !ok {
        perr = &PaymentError{Reason: "insufficient balance"}
    }
    return perr // on success: a typed nil, wrapped in a non-nil error
}
Enter fullscreen mode Exit fullscreen mode
1. pay(true) == nil: false | dynamic type: *main.PaymentError
   payFixed(true) == nil: true
Enter fullscreen mode Exit fullscreen mode

pay(true) succeeded, yet err != nil is true, so every caller treats a successful payment as a failure. The interface holds the pair (*PaymentError, nil), and an interface is only nil when both halves are empty. The fix is to return a literal nil on success and the concrete error only on failure (payFixed). Callers who need the details use errors.As, which still works:

   errors.As finds *PaymentError in pay(false): true insufficient balance
Enter fullscreen mode Exit fullscreen mode

Rule: a function whose result type is an interface (error, io.Reader, …) should never return a typed nil. Return nil itself.

Problem 1: a goroutine panicked and took the program down

Old thinking: exceptions bubble up until someone catches them. Here, main has a deferred recover, so surely it catches a panic from a goroutine it started?

func main() {
    defer func() { fmt.Println("main recovered:", recover()) }()
    go func() {
        panic("payment worker failed")
    }()
    time.Sleep(100 * time.Millisecond)
    fmt.Println("main finished")
}
Enter fullscreen mode Exit fullscreen mode
panic: payment worker failed

goroutine 6 [running]:
Enter fullscreen mode Exit fullscreen mode

Neither "main recovered" nor "main finished" ever prints. A panic unwinds only its own goroutine's stack. The goroutine has no relationship to the function that started it: there is no parent stack to unwind into. When an unrecovered panic reaches the top of any goroutine, the whole program exits.

Flow thinking: the panic flows up its goroutine, and nobody is there to receive it. If a goroutine can panic, recover must be deferred inside that goroutine:

func safeGo(fn func()) {
    go func() {
        defer func() {
            if r := recover(); r != nil {
                log.Printf("goroutine panicked: %v", r)
            }
        }()
        fn()
    }()
}
Enter fullscreen mode Exit fullscreen mode

Use this at the edges (a worker pool, a request handler), and send the error somewhere a human or a supervisor will see it. Recovering and logging is not the same as handling; it just keeps one bad request from killing every other request in flight.

Problem 2: the map that can't be shared

Go maps are not safe for concurrent writes. The runtime actively checks for it, and what happens is worse than a panic:

func main() {
    defer func() { fmt.Println("recovered?", recover()) }()
    m := map[int]int{}
    var wg sync.WaitGroup
    for g := 0; g < 8; g++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 100000; i++ {
                m[i] = i
            }
        }()
    }
    wg.Wait()
}
Enter fullscreen mode Exit fullscreen mode
fatal error: concurrent map writes

goroutine 12 [running]:
Enter fullscreen mode Exit fullscreen mode

fatal error, not panic. "recovered?" never prints: a fatal error cannot be recovered. The runtime decided the map's internal state may be corrupt and that continuing would be worse than stopping. (This detection is best-effort; a race that the check misses can silently corrupt data instead, which is why go test -race exists.)

Ownership thinking gives two clean fixes:

A single owner. One goroutine owns the map; everyone else asks it through a channel:

type op struct {
    key  string
    resp chan int
}

func mapOwner(ops <-chan op) {
    m := map[string]int{}
    for o := range ops {
        m[o.key]++
        o.resp <- m[o.key]
    }
}
Enter fullscreen mode Exit fullscreen mode

A guarded owner. The map stays shared, but a mutex makes every access exclusive:

var mu sync.Mutex
mu.Lock()
m["k"]++
mu.Unlock()
Enter fullscreen mode Exit fullscreen mode

Measured: channel owner vs mutex

"Share memory by communicating" is a Go proverb, and it's sometimes read as "always use channels". Both versions above, hammered from all 8 cores:

BenchmarkChannelOwner-8      4767484           250.3 ns/op         0 B/op          0 allocs/op
BenchmarkMutex-8             9130184           131.8 ns/op         0 B/op          0 allocs/op
Enter fullscreen mode Exit fullscreen mode

The mutex is about twice as fast here: each channel operation is a round trip (send the request, wait for the reply) through the scheduler, while the mutex is a lock and an unlock. So:

  • Use a mutex to protect a piece of state: a cache, a counter, a map.
  • Use channels to transfer ownership or coordinate work: pipelines, worker pools, signalling "done".
  • When the owner goroutine does real work per request (I/O, a state machine), the channel's overhead disappears into it, and the clearer ownership often wins.

Both are ownership: one says "only the holder of this lock may touch it", the other says "only this goroutine may touch it".

Ownership in a real system

The model scales. In Kengele, an open-source alarm for activists that I build in Go, the component that decides when someone has missed a check-in is designed around ownership from the first line:

// The engine is passive and has no goroutines: the caller feeds it the
// time (Tick), connectivity changes (SetTransport, SetOnline) and opened
// messages (Observe), and acts on the Notices it returns. That keeps it
// deterministic under a fake clock.
Enter fullscreen mode Exit fullscreen mode
  • One owner. Only the engine's own methods change its state, called by one caller at a time. No locks needed, and a test fails if anyone adds a goroutine to it.
  • Explicit flow. Inputs come in as method arguments (time, network changes, messages); decisions come out as return values ([]Notice). There's no hidden channel, callback or global.
  • Copies at the boundary. When other code needs the engine's list of activists, it gets a copy, never the engine's own slice.
  • Where sharing is real, a mutex. The guardian-confirmation tally does receive messages from many goroutines, so it holds one sync.Mutex around all its state, and its tests run under the race detector.

Ownership and flow aren't a teaching device. They're how you make a system that has to be right on the worst day of someone's life also easy to test.


Run everything yourself

Four small experiments, Go 1.21 or newer. The benchmarks:

own_test.go (click to expand)
package own

import (
    "sync"
    "testing"
)

type BigStruct struct{ Data [1024]int }

//go:noinline
func byValue(b BigStruct) int { return b.Data[0] + b.Data[1023] }

//go:noinline
func byPointer(b *BigStruct) int { return b.Data[0] + b.Data[1023] }

var sink int

func BenchmarkByValue(bm *testing.B) {
    var b BigStruct
    for i := 0; i < bm.N; i++ {
        sink += byValue(b)
    }
}

func BenchmarkByPointer(bm *testing.B) {
    var b BigStruct
    for i := 0; i < bm.N; i++ {
        sink += byPointer(&b)
    }
}

type op struct {
    key  string
    resp chan int
}

func BenchmarkChannelOwner(bm *testing.B) {
    ops := make(chan op)
    go func() {
        m := map[string]int{}
        for o := range ops {
            m[o.key]++
            o.resp <- m[o.key]
        }
    }()
    bm.RunParallel(func(pb *testing.PB) {
        r := make(chan int)
        for pb.Next() {
            ops <- op{"k", r}
            <-r
        }
    })
    close(ops)
}

func BenchmarkMutex(bm *testing.B) {
    var mu sync.Mutex
    m := map[string]int{}
    bm.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            mu.Lock()
            m["k"]++
            mu.Unlock()
        }
    })
}
Enter fullscreen mode Exit fullscreen mode

go mod init own
go test -bench . -benchmem
Enter fullscreen mode Exit fullscreen mode

For escape analysis, put the two newUser functions in a main package and run go build -gcflags=-m .. For the map race and the goroutine panic, run the two main functions above with go run .: both should crash, and that's the point. Your numbers will differ from mine (Apple M1); the ratios are what matter.

Quick reference

Ownership

If you want to... Do this Because
Modify a struct in a function Pass *T Otherwise you modify a copy
Avoid copying a large struct Pass *T (measure first for small ones) 8 KB by value was ~90× slower than a pointer
Keep the original unchanged Pass by value The function gets an independent copy
Protect shared state sync.Mutex Simple, and ~2× faster than a channel round trip here
Transfer work or ownership A channel The send says who owns it now
Know where a value lives go build -gcflags=-m Pointers can force heap allocation

Flow

Pattern Direction
Function call Arguments in, return values out
Error Up the stack, one return err at a time
Channel From sender to receiver
Panic Up its own goroutine only; unrecovered, it ends the program
Concurrent map write Nowhere: fatal error, not recoverable
Value into an interface Copied in; later changes to the original don't reach it
Context cancellation Down the tree of derived contexts

Final thought

Ownership and flow. Ask who owns each value and which way it moves, and goroutines, channels, interfaces, errors and performance all start to look like consequences instead of rules to memorise.

A note on this revision: the first version of this post (June 2026) ended with a "what other Go developers learned" section of reader quotes and a newsletter-style homework section. I removed them because I couldn't stand behind them as written, and replaced assertions with measurements. If a number here is wrong on your machine, tell me in the comments.

Top comments (0)