Go: invalid memory address or nil pointer dereference
Most nil panics are a typed nil in an interface or a value used after an error. How each shape fails, how to return nil properly, and which stack trace detail names the cause.

Introduction & Quick Summary
Symptom. A Go service exits with:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4b7c21]
goroutine 1 [running]:
main.loadUser(...)
/app/user.go:23 +0x21The line it points at is frequently a plain field read, a method call, or an err.Error() inside a logging line.
Cause. A pointer is nil and the code reads through it. In Go this is a runtime panic, not a compile error, and the language offers no exception: the process dies unless a recover is in the call stack. The interesting cases are not the obvious ones — they are the typed nil hidden inside an interface, the value returned alongside an error that was ignored, and the nil receiver whose method assumed otherwise.
Fix. Return nil for the interface, not a typed nil; never use a value whose error is non-nil; guard receiver methods that can see a nil pointer; and use errors.Is rather than comparing interfaces. Section 4 shows each with the stack trace it produces.
Core Mechanics, Signatures & Reproducible Setup
A nil pointer has a type and no address. Reading a field or calling a method with a pointer receiver dereferences it, and that is where the runtime panics. A method with a value receiver dereferences immediately too, because the value must be copied — which is why func (p *T) String() on a nil *T can work if it checks p == nil first, while func (t T) String() cannot.
A reproduction of the three common shapes, in one file:
package main
import "fmt"
type User struct{ Name string }
func (u *User) Label() string {
if u == nil {
return "<nil user>"
}
return u.Name
}
func main() {
var u *User
fmt.Println(u.Label()) // fine: method handles nil
fmt.Println(u.Name) // panic: invalid memory address or nil pointer dereference
m := map[string]int{}
m["a"] = 1 // fine
var m2 map[string]int
m2["a"] = 1 // panic: assignment to entry in nil map
}The panic message tells you which of the two you have: a nil dereference names the signal and prints the goroutine stack, while a nil map write says assignment to entry in nil map and is a different fix.
Debugging flags that turn a one-line panic into something usable:
GOTRACEBACK=all go test ./... # every goroutine, not just the crashing one
GOTRACEBACK=crash ./service # core dump for a debugger
go build -trimpath -gcflags="all=-N -l" ./cmd/service # no inlining, for dlv-N -l disables inlining so the stack frame names the function you wrote rather than a compiler-generated wrapper.
Key Comparison Table
Nil values differ by type, and the difference decides whether you get a panic, a block, or nothing:
| Nil value | Read | Write | Notes |
|---|---|---|---|
*T (pointer) | panic on field read | panic | Method with nil check is safe |
map[K]V | returns zero value, safe | panic assignment to entry in nil map | make() before writing |
[]T (slice) | len 0, range safe | append safe | No panic; only indexing panics |
chan T | blocks forever | blocks forever | fatal error: all goroutines are asleep |
func() | panic on call | — | Check before calling |
| interface with nil type | panic on method call | — | if x == nil is true |
| interface with typed nil | calls the method | — | if x == nil is false |
Two ways to test an interface for nilness:
| Expression | True for typed nil? | Use |
|---|---|---|
err == nil | No | Normal error check |
reflect.ValueOf(err).IsNil() | Yes | Diagnostics only |
err != nil after returning nil explicitly | Consistent | The fix, at the producer |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. The typed nil inside an interface
This is the bug that survives code review. A nil pointer of a concrete type stored in an interface is not a nil interface, because the interface holds a type:
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return "invalid: " + e.Field }
func validate(name string) error {
var vErr *ValidationError
if name == "" {
vErr = &ValidationError{Field: "name"}
}
return vErr // BUG: returns a typed nil, not nil
}
func main() {
err := validate("ok")
fmt.Println(err == nil) // false
fmt.Println(err.Error()) // panic: nil pointer dereference in Error()
}Two valid fixes. Return the interface value only when there is an error, or make Error() nil-safe:
func validate(name string) error {
if name == "" {
return &ValidationError{Field: "name"}
}
return nil // untyped nil: err == nil is true
}
func (e *ValidationError) Error() string {
if e == nil {
return "<nil validation error>"
}
return "invalid: " + e.Field
}The second is a safety net, not the fix; if err != nil branches still misbehave.
2. Using the value returned with an error
resp, err := http.Get(url) returns a nil resp when err != nil, and the panic arrives one line later inside a deferred close or a field read:
resp, err := client.Do(req)
defer resp.Body.Close() // panic when err != nil: resp is nil
if err != nil {
return err
}resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("fetch %s: %w", url, err)
}
defer resp.Body.Close()The same shape appears with sql.Open followed by db.Ping, and with JSON decoding into a pointer that was never allocated. go vet and staticcheck flag some of these, not all.
3. Nil receivers that are legitimate
Go allows methods on nil receivers, and several standard types rely on it: (*sync.Mutex)(nil) panics, but a nil *bytes.Buffer is not usable either — the idiom is your own type with an explicit check:
type Tree struct {
Left, Right *Tree
Value int
}
func (t *Tree) Sum() int {
if t == nil {
return 0
}
return t.Value + t.Left.Sum() + t.Right.Sum()
}Reading t.Left.Sum() when t.Left is nil is safe precisely because the method checks first. The panic comes from a method that assumes a non-nil receiver, so treat "can this be nil?" as a property of the method, not of the call site.
4. Nil map writes
A zero-value struct that is expected to collect results holds a nil map, and the first assignment panics with a different message:
type Stats struct{ byRoute map[string]int }
func (s *Stats) Add(route string) {
if s.byRoute == nil {
s.byRoute = make(map[string]int) // lazy init
}
s.byRoute[route]++
}Reading from a nil map is legal and returns the zero value, so a struct that only reads works in tests and panics on the first real write — the reason this bug ships. Initialize maps in the constructor (Stats{byRoute: map[string]int{}}) and keep the lazy check for value-typed zero structs.
5. Nil channels and the deadlock panic
A nil channel blocks forever. In a worker loop that receives from a channel which was never assigned, the runtime reports fatal error: all goroutines are asleep - deadlock! instead of a nil panic, and the stack shows chan receive on a nil channel:
var jobs chan Job // nil
go func() {
for j := range jobs { // blocks forever
process(j)
}
}()
// fatal error: all goroutines are asleep - deadlock!jobs := make(chan Job, 16) // buffered, non-nilThe distinction matters when reading a stack trace: a deadlock with chan receive on a nil channel is a variable that was never initialized, not a missing close.
6. Finding the nil in a large codebase
When the stack points into generated code or an interface method, narrow it with a wrapped panic and structured logs:
func loadUser(ctx context.Context, id string) (*User, error) {
u, err := repo.Find(ctx, id)
if err != nil {
return nil, fmt.Errorf("loadUser %s: %w", id, err)
}
if u == nil {
return nil, fmt.Errorf("loadUser %s: repository returned nil user without error", id)
}
return u, nil
}The second check is the important habit: a repository that returns (nil, nil) for "not found" is the most common source of a nil dereference far from the query, and an explicit error at the boundary names the row in the message. Delve's dlv test with a breakpoint on the panicking line, plus print u, is faster than reading code once the line is local.
Common Compilation/Runtime Mistakes & Version Gotchas
var vErr *MyError; return vErr. A typed nil in an interface makeserr != niltrue for a call that succeeded; return a barenil.- Comparing errors with
==. Wrapped errors are never equal to the sentinel;errors.Iswalks the chain, and a nil check on the wrapped value is not a substitute. defer resp.Body.Close()before the error check. The defer evaluates its receiver immediately, so a nilresppanics at function exit even if the error is returned correctly.- Shadowing
errinside anif.if err := f(); err != nil { ... }then using the outererrafter the block reads a stale value and the nil check passes for the wrong reason. - Recovering to hide the panic.
defer func(){ recover() }()at the top of a handler turns a nil dereference into a 200 with an empty body; log the stack withruntime/debug.Stack()and return 500. - Assuming
recoverworks across goroutines. A panic in a goroutine started withgo func()kills the process unless that goroutine recovers; the handler's recover covers only its own stack. - Nil checks in tests only. Table tests with zero-value structs pass because the code path is short; the nil arrives from a database read or an HTTP response, so the regression test needs that shape.
- Generics do not help.
func First[T any](s []T) Treturns a zero value that may be a nil pointer; returning(T, bool)is the idiom that forces the caller to check.
Related tools. When a nil comes from an API response, paste the JSON into the JSON formatter to see whether the field was absent, null, or an empty string — Go decodes all three into very different values — and diff the request and response bodies with the text diff tool when a client starts receiving null for a field it has always assumed present.
Official references
primary documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesmissing go.sum entry and inconsistent vendoring: Go Module Fixes
Readonly module mode will not repair your files. go mod tidy fixes the checksums, go mod vendor fixes the tree, and neither belongs in CI as a workaround.
Go http.Client: unexpected EOF and Connection Reuse Leaks
A body closed without being read cannot be reused, and descriptors pile up. Idle timeouts shorter than the upstream's, MaxIdleConnsPerHost and safe retries.
Go context.DeadlineExceeded vs Canceled and Goroutine Leaks
A deadline is retryable and a cancellation is not, and both arrive wrapped. The errors.Is checks, the four handler timeouts, and the goroutine dump that names the leak.
Go Module Errors: Checksum Mismatch, 404s, and Proxy Failures
A checksum mismatch is not a cache bug. Separate the proxy, the sum database, and go.sum, then fix the layer the message names instead of editing the hash.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.