Go

Fix Go "panic: runtime error: invalid memory address or nil pointer dereference" — Nil Receivers, Returned Nil Pointers, and Typed Nil Interfaces

This panic means a pointer was used before anything was stored at the address it was supposed to hold: the pointer itself is nil, so the field read, the write, or the method body has no value to work on. Each section below takes one shape — a declared pointer that was never assigned, a write through a nil pointer, a method call on a nil receiver, a function that returned nil, a chain through a nil field, a typed nil hiding in an interface — shows the exact output it prints, and gives the fix that puts a value behind the pointer or checks for nil before the use.

Written November 20, 2026 · Tested with Go 1.26.4 · 20 min read

By the end of this guide
  • The first failure: a field of a pointer that was never assigned
  • Reading the message: the signal line and the trace
  • Writing through a nil pointer: assignment is also a dereference
  • A method call on a nil receiver: the call succeeds, the body fails

What this guide is

panic: runtime error: invalid memory address or nil pointer dereference is a run-time panic: the program built, started, and then used a pointer whose value is nil. The specification states the core rule under address operators: for an operand x of pointer type *T, the indirection *x denotes the value pointed to by x, and if x is nil, an attempt to evaluate *x causes a run-time panic. A field access through a pointer, such as u.Name where u is a *User, is an implicit dereference, so it lands on the same rule. Every shape in this guide is that one rule met from a different direction: a pointer declared and never given a value, a pointer a function returned as nil on one path, a pointer field inside a struct that was itself allocated, and a nil pointer that an interface check failed to catch.

Where the nil comes from is also in the specification. When storage is allocated for a variable and no explicit initialization is provided, the variable is given the zero value for its type, and the zero value for pointers, functions, interfaces, slices, channels, and maps is nil. So var u *User does not hold an empty User; it holds nil, and it stays nil until the program assigns a pointer to a real value, with &User{...}, with new, or with the result of a function that returns one. The compiler accepts every program in this guide, because a pointer variable is allowed to hold nil. The defect is not the declaration; it is the use that arrives before the assignment, or on a path where the assignment never ran.

The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:

Terminal
$ mkdir nilptr
$ cd nilptr
$ go mod init example.com/nilptr
go: creating new go.mod: module example.com/nilptr

Each program that follows replaces the contents of that main.go. The panic transcripts are shown as printed by go run -trimpath main.go: the -trimpath flag only changes how file positions print in the trace — ./main.go:11 here, where a plain run prints the same line number behind the full directory path on your machine. Tested with Go 1.26.4.

The first failure: a field of a pointer that was never assigned

The smallest program that earns the panic declares a pointer, assigns nothing to it, and reads a field through it:

Go
// main.go
package main

import "fmt"

type User struct {
    Name string
}

func main() {
    var u *User
    fmt.Println(u.Name)
}
Terminal
$ go run -trimpath main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e196]

goroutine 1 [running]:
main.main()
    ./main.go:11 +0x16
exit status 2

u.Name reads as a field access, and Go lets it be written without an explicit *u because the pointer is dereferenced implicitly. That convenience hides the step that fails: there is no User value behind u, so there is no Name field to read. The runtime raises the panic at the access. The declaration is the trap's first half, because var u *User looks like it creates a user. It creates a pointer variable and sets it to nil, the zero value for its type, and nothing else happens until an assignment the program never makes.

The fix for this shape is to assign before the use: u := &User{Name: "Ana"} creates the value and takes its address in one step, and u := new(User) allocates a zero User and returns its address for fields the program fills in afterward. Which one fits depends on whether the fields are known at the creation point. What does not fix it is a check added at this line alone when every path through the program needs the value: a pointer that is always supposed to hold a value should be created holding one, at the declaration, so the nil state is never available to the code that follows.

Reading the message: the signal line and the trace

This panic carries a second line that the index and map panics do not: [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e196]. The runtime attempted the access at address 0, which is what dereferencing nil means at the machine level, and the operating system's fault arrives back as a SIGSEGV signal that the runtime reports alongside the panic. Three parts of the output are worth reading.

First, addr=0x0 is the confirmation that the pointer was nil rather than merely wrong. A pointer that holds a stale or computed address fails at some other address; address 0 is nil itself, so the search is for a pointer that was never assigned or was assigned nil, not for pointer arithmetic gone wrong, which Go does not permit outside the unsafe package in any case.

Second, the pc= value and the +0x16 offset are machine addresses for this build of this program. They identify the instruction that faulted, and they change when the program changes. They are not the diagnostic; the file and line under main.main() are.

Third, the trace names the line where the nil pointer was used, ./main.go:11 here, and says nothing about where the nil came from. That gap is the work of this guide: the use site is where the panic prints, and the cause is upstream, at a declaration with no assignment, a return statement on a path the caller did not expect, or a field nobody set. Read the trace for the use, then walk back to every place that pointer could have received its value and find the path where it received none.

Writing through a nil pointer: assignment is also a dereference

Reading is not the only direction that fails. Writing through a nil pointer panics at the assignment:

Go
// main.go
package main

import "fmt"

func main() {
    var p *int
    *p = 42
    fmt.Println(*p)
}
Terminal
$ go run -trimpath main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e190]

goroutine 1 [running]:
main.main()
    ./main.go:7 +0x10
exit status 2

*p = 42 needs a variable of type int for the 42 to land in, and p points at none. This shape appears in real code when a pointer is passed into a helper that is expected to fill it, or when a pointer field or a pointer result is treated as pre-allocated storage. The repair is the same allocation step, placed before the write: p := new(int) returns a pointer to a fresh zero int, after which *p = 42 stores into real storage and the read prints 42. The fixed program at the end of this guide includes exactly this pair. A pointer is an address, not the storage at that address, and every write through one assumes the storage was created by an earlier step in the program.

A method call on a nil receiver: the call succeeds, the body fails

A method call on a nil pointer receiver does not panic at the call. It panics inside the method, at the first use of the receiver:

Go
// main.go
package main

import "fmt"

type Counter struct {
    n int
}

func (c *Counter) Inc() {
    c.n++
}

func main() {
    var c *Counter
    c.Inc()
    fmt.Println("done")
}
Terminal
$ go run -trimpath main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e191]

goroutine 1 [running]:
main.(*Counter).Inc(...)
    ./main.go:10
main.main()
    ./main.go:15 +0x11
exit status 2

The trace shows both frames: main.main() at line 15 made the call, and main.(*Counter).Inc(...) at line 10, the c.n++ line, is where the panic fired. Calling a method on a nil pointer receiver is legal Go; the receiver value nil is passed into the method like any other receiver value. The method body decides what happens next. Inc writes a field of the value behind c, there is no such value, and the write is the dereference that panics.

A method that checks its receiver first turns the same call into defined behavior:

Go
// main.go
package main

import "fmt"

type Counter struct {
    n int
}

func (c *Counter) Value() int {
    if c == nil {
        return -1
    }
    return c.n
}

func main() {
    var c *Counter
    fmt.Println(c.Value())
}
Terminal
$ go run -trimpath main.go
-1

The program prints -1 and exits cleanly: Value compares its receiver against nil before touching a field, and returns a sentinel for the nil case. This is a deliberate design choice, not a universal rule for methods. It fits methods where nil has a sensible meaning, such as a zero or empty reading from an absent value. It does not fit a method like Inc, whose whole job is to mutate the value behind the receiver; no sentinel fixes a write that has nowhere to land, and the repair there belongs at the call site, where the Counter should have been allocated. When a trace shows a panic inside a method frame with a call from a frame below it, the two candidate fixes are these two, and the method's job decides which one is right.

A function that returns nil: the panic moves to the caller

A pointer does not have to be declared nil in the function that uses it. It can arrive nil from a function whose other paths return a real value:

Go
// main.go
package main

import "fmt"

type User struct {
    Name string
}

func findUser(id int) *User {
    if id < 0 {
        return nil
    }
    return &User{Name: "Ana"}
}

func main() {
    u := findUser(-1)
    fmt.Println(u.Name)
}
Terminal
$ go run -trimpath main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e196]

goroutine 1 [running]:
main.main()
    ./main.go:18 +0x16
exit status 2

The trace names only main.main() at line 18, the field access. findUser returned normally; returning nil is not an error in itself, and nothing in its frame is on the stack when the panic fires. The contract is the issue: findUser can return nil, for the negative ID here, standing in for the not-found, not-loaded, and not-configured cases in real code, and the caller used the result as if nil were impossible. Lookup and factory functions that return a bare pointer put this obligation on every caller, and the obligation is easy to miss because the success path reads so cleanly.

Two repairs cover this shape, and mature Go code leans on the second. The first is the caller-side check: if u == nil before the use, with the nil case handled as the absence it represents. The second is to change the function's shape so absence is carried in the return values: func findUser(id int) (*User, bool) or (*User, error), where the second value forces the caller to confront the missing case at the call site instead of discovering it in a panic trace. Where the function is yours to change, the two-value form is the stronger fix, because a bare pointer return makes the nil path invisible in the caller's code. Where it is not yours, the check at every call site is the fix, and a wrapper that converts the result into the two-value form at your boundary keeps the checks in one place.

A chain through a nil field: the outer value exists, the inner pointer does not

Allocating the outer struct does not allocate the pointer fields inside it. Each pointer field starts at its zero value, nil, until it is assigned separately:

Go
// main.go
package main

import "fmt"

type Address struct {
    City string
}

type User struct {
    Addr *Address
}

func main() {
    u := &User{}
    fmt.Println(u.Addr.City)
}
Terminal
$ go run -trimpath main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e1a2]

goroutine 1 [running]:
main.main()
    ./main.go:15 +0x22
exit status 2

Here u is a real pointer to a real User; the first link of the chain works. u.Addr is nil, because the composite literal &User{} zeroed every field it did not name, and pointer fields zero to nil. The second link, .City, is the dereference that panics. The trace line, 15, is the whole expression; the message does not say which link was nil, so a chain failure is read by breaking the expression apart: the nil link is the first pointer in the chain that the construction code did not assign.

The fixes are construction and checking, in that order. Construction: name the field in the literal, &User{Addr: &Address{City: "Dawson Creek"}}, or assign u.Addr = &Address{...} before the chain is walked, so the value the code expects is built where the outer value is built. Checking: where an inner pointer is legitimately optional, test that link, if u.Addr != nil, before the access past it, and treat the nil case as the missing data it is. Long chains through optional pointers are where this panic recurs most in data-shaped code, because each link looks as solid as the one before it and only the construction site knows which links were actually filled.

A typed nil in an interface: the nil check that passes and still panics

The subtlest shape stores a nil pointer in an interface value. The interface then compares as not nil, and code that trusts the comparison walks into the dereference it was guarding against:

Go
// main.go
package main

import "fmt"

type User struct {
    Name string
}

func main() {
    var u *User
    var v interface{} = u
    fmt.Println(v == nil)
    fmt.Println(v != nil)
}
Terminal
$ go run -trimpath main.go
false
true

The program prints false for v == nil and true for v != nil, even though u is nil. The specification's own example is this case: a variable v of type *T has value nil, and after x = v, the interface variable x has value (*T)(nil) and dynamic type *T. An interface value carries a type as well as a value, and it is nil only when both are absent. Storing a typed nil pointer fills the type half, so the comparison against nil is false. The pointer inside is still nil, and any use that dereferences it panics:

Go
// main.go
package main

import "fmt"

type User struct {
    Name string
}

func describe(v interface{}) {
    if v == nil {
        fmt.Println("nil")
        return
    }
    u := v.(*User)
    fmt.Println(u.Name)
}

func main() {
    var u *User
    describe(u)
}
Terminal
$ go run -trimpath main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e1bb]

goroutine 1 [running]:
main.describe({0x4a5d20?, 0x0?})
    ./main.go:15 +0x3b
main.main()
    ./main.go:20 +0x1c
exit status 2

describe does check: v == nil is false for the typed nil, the guard passes, the type assertion succeeds because the dynamic type really is *User, and u.Name dereferences the nil pointer the assertion faithfully returned. The trace even shows the pair the interface carried, a type word and a value word of 0x0. The repair belongs where the typed nil is produced: return an untyped nil, or do not return the pointer at all on the path where it was never set, so the interface the caller receives is genuinely nil. A function whose contract is "nil when there is nothing" must return the literal nil on that path, not a variable of pointer type that happens to hold nil. Inside the receiving function, a type switch or assertion that extracts a pointer inherits the obligation to check that pointer itself, because the interface check cannot do it.

The contrast: a panic can be recovered

Like the index panic, this panic is an ordinary panic once the runtime raises it, and a deferred recover catches it:

Go
// main.go
package main

import "fmt"

type User struct {
    Name string
}

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered:", r)
        }
    }()
    var u *User
    fmt.Println(u.Name)
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
recovered: runtime error: invalid memory address or nil pointer dereference

The deferred function prints the recovered value, the panic message without the signal line, and the program exits cleanly; after does not print, because the panic still unwound the function that raised it. The legitimate uses are the same as for any panic: a probe that confirms which access in a suspect path fails, and a boundary guard around work the program does not control. Around the program's own pointer use, recover is the wrong tool for the same reason it is wrong around an index: the nil check states the condition at the point of use and handles the case where it stands, for the cost of one comparison, while the recovered version learns the same fact by unwinding and still owes the caller an answer about the value it failed to reach.

The fixed program

One program that applies each fix at once: the two-value style handled with a caller check where a lookup returns nil, the found case used directly, and a new allocation behind a write through a pointer:

Go
// main.go
package main

import "fmt"

type User struct {
    Name string
}

func findUser(id int) *User {
    if id < 0 {
        return nil
    }
    return &User{Name: "Ana"}
}

func main() {
    u := findUser(-1)
    if u == nil {
        fmt.Println("no user for id -1")
    } else {
        fmt.Println(u.Name)
    }

    u = findUser(7)
    fmt.Println(u.Name)

    p := new(int)
    *p = 42
    fmt.Println(*p)
}
Terminal
$ go run main.go
no user for id -1
Ana
42

The first lookup takes the branch the panic would have replaced, and prints the absence as a fact about the input: no user for ID -1. The second lookup returns a real pointer, and its field reads directly, with no check standing between the call and the use on a path where the check already happened by construction of the example. The new(int) allocation gives the write a destination, and the read prints the stored 42. Nothing in the program recovers, and nothing needs to: each pointer is either checked at the point where nil is a possible value or created holding a value before its first use.

The fixes, ranked

Create the value where the pointer is declared, when the pointer is not meant to be optional. u := &User{...} or u := new(User) at the declaration removes the nil state from the program entirely for that variable. This is ranked first because it is the construction fix: code that cannot hold nil cannot dereference nil, and most declared-then-used pointers in ordinary code were never meant to be optional in the first place.

Check at the point where nil is a possible value. if u == nil before the use, at call sites of functions that can return nil, at links of a chain that are legitimately optional, and inside methods designed to accept a nil receiver. The check belongs at the boundary where the nil can arrive, not scattered at every later use of a value already proven non-nil.

Return absence in the return values, not in a bare pointer. A lookup that can come back empty should return (*User, bool) or (*User, error), so the caller handles the empty case as part of the call. Where an existing bare-pointer function cannot change, wrap it once at your boundary and check inside the wrapper.

Never let a typed nil stand in for nil. A function returning an interface should return the literal nil on the empty path, not a pointer variable holding nil. Code receiving a pointer out of an interface checks that pointer, not only the interface, before dereferencing it.

Do not answer the panic with recover in code that owns the pointer. The recovered program above is a probe and a boundary pattern. Around your own dereferences, recover converts a one-line check into an unwinding, discards the state the program was in, and leaves the missing value just as missing.

Which fix for which cause

What the message and code show Cause Fix
Field read on a var u *User that is never assigned The declaration set the pointer to its zero value, nil Assign &User{...} or new(User) at the declaration
Panic at a *p = ... write A write through a pointer with no storage behind it Allocate first, with new or the address of a variable
Panic frame inside a method, call frame below it A method used its receiver while the receiver was nil Allocate at the call site, or make the method nil-safe by design
Panic at the first use after a function call The function returned nil on a path the caller did not handle Check the result, or return (*T, bool) / (*T, error)
Panic on a chain such as u.Addr.City An inner pointer field was left at its zero value Build the inner value in the literal, or check that link
A nil check passed and the dereference still panicked A typed nil pointer stored in an interface Return literal nil; check the extracted pointer itself

Checklist

  • Read addr=0x0 as the diagnosis: the pointer was nil, so look for a missing assignment, not a wrong address.
  • Take the trace line as the use site only, then walk back to every place that pointer could have received a value and find the path where it received none.
  • Audit declarations: every var x *T with no assignment before its first use is this panic waiting for the input that reaches it.
  • Audit returns: every function that returns a bare pointer gets a documented answer to what nil means and a check, or a second return value, at its call sites.
  • Audit chains link by link: an allocated outer struct says nothing about its pointer fields, which start nil until they are built or assigned.
  • Audit interface boundaries: a value that crossed an interface and came out as a pointer gets its own nil check, because the interface comparison cannot see a typed nil.

Sources

  • The Go Programming Language Specification — for address operators (for an operand x of pointer type *T, *x denotes the variable of type T pointed to by x, and if x is nil, an attempt to evaluate *x causes a run-time panic), for the zero value (storage allocated with no explicit initialization is given the zero value for its type, which is nil for pointers, functions, interfaces, slices, channels, and maps), and for variables and dynamic types (a variable of type *T can hold the value nil, and assigning it to an interface variable gives the interface that dynamic type with the value (*T)(nil), so the interface itself is not nil).

Keep Exploring