Skip to main content

How to Check if a Pointer Is nil in Go

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

In Go, a pointer that points to nothing is nil, and reading a field through it stops the program with an invalid memory address or nil pointer dereference panic. Check it with if plan == nil first, and return or use a default when it is.

Syntax​

Syntax
if <pointer> == nil {
<what to do when it points to nothing>
}
PartWhat it does
<pointer>A pointer variable, such as one of type *Plan.
== nilTrue when the pointer points to nothing. != nil is true when it points to a value.
<what to do when it points to nothing>Usually a return with a default, so the code after the if runs only with a real value.

The Go specification, Pointer types: "The value of an uninitialized pointer is nil." Its Comparison operators add: "Pointer types are comparable. Two pointer values are equal if they point to the same variable or if both have value nil."

The Example​

The example's describe function takes a pointer to a Plan and returns a short description of the plan, or no plan when the pointer is nil. It describes a pro plan, then a pointer that was declared but never set. A changed version then removes the check.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which declares a Plan struct and a describe function that returns no plan when its Plan pointer is nil and the plan's name and limit otherwise, then prints describe for a pointer to a pro plan, describe for a nil pointer, and whether that pointer is nil.

main.go
package main

import "fmt"

type Plan struct {
Name string
Limit int
}

func describe(plan *Plan) string {
// A nil pointer points to no Plan, so check it before reading a field through it.
if plan == nil {
return "no plan"
}
return fmt.Sprintf("%s plan, limit %d", plan.Name, plan.Limit)
}

func main() {
pro := &Plan{Name: "pro", Limit: 500}
var none *Plan // a pointer that points to nothing: nil

fmt.Println(describe(pro))
fmt.Println(describe(none))
fmt.Println(none == nil)
}

&Plan{Name: "pro", Limit: 500} makes a Plan and gives a pointer to it. var none *Plan declares a pointer without setting it.

Step 2: Run It​

Terminal
go run main.go
Output
pro plan, limit 500
no plan
true

The command is the same in zsh, bash and PowerShell.

Step 3: Remove the Check​

Replace main.go with a version whose describe reads the fields without checking the pointer:

main.go
package main

import "fmt"

type Plan struct {
Name string
Limit int
}

func describe(plan *Plan) string {
return fmt.Sprintf("%s plan, limit %d", plan.Name, plan.Limit)
}

func main() {
var none *Plan // a pointer that points to nothing: nil

fmt.Println(describe(none))
}
Terminal
go run main.go
Output
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x104534c68]

goroutine 1 [running]:
main.describe(...)
/Users/Shared/you/main.go:11
main.main()
/Users/Shared/you/main.go:17 +0x28
exit status 2

A zsh terminal where go run main.go prints pro plan, limit 500, then no plan, then true; for the changed file it stops with panic: runtime error: invalid memory address or nil pointer dereference, a SIGSEGV line, a trace through main.describe and main.main, and exit status 2.

What Happened​

  • describe(pro) read the fields through the pointer and returned pro plan, limit 500. For a pointer to a struct, plan.Name is shorthand: the specification's Selectors say that "x.f is shorthand for (*x).f".
  • describe(none) returned no plan. none was never set, so it was nil, and the if returned before any field was read.
  • none == nil printed true.
  • Without the check, the program stopped. plan.Name read a field through a nil pointer, and the specification says that "If x is of pointer type and has the value nil and x.f denotes a struct field, assigning to or evaluating x.f causes a run-time panic." The trace shows where: main.describe(...) at main.go:11, the line that read plan.Name, called from main.main() at main.go:17. go run then printed exit status 2.

Common Mistakes​

MistakeWhat happensDo this instead
Reading a field before checking for nilpanic: runtime error: invalid memory address or nil pointer dereferenceCheck == nil first and return
Putting the field first in a combined condition, as in plan.Limit > 100 && plan != nil&& evaluates its left side first, so the field is read and it still panicsPut the check on the left: plan != nil && plan.Limit > 100 gave false for a nil plan, with no panic
Comparing an any that holds a nil pointer with nilfalse: a nil *Plan stored in a variable of type any gave p == nil as true but v == nil as falseCheck the pointer itself, before you store it in an interface
Expecting new(Plan) or &Plan{} to be nilBoth point to a real Plan with empty fields, so == nil is falseUse var plan *Plan for "no plan"

Troubleshooting​

SymptomLikely causeFix
panic: runtime error: invalid memory address or nil pointer dereferenceA field was read through a nil pointerFind your function's line in the trace, and check the pointer for nil before it
if v == nil is false, but the value inside is a nil pointerv is an interface, such as any or error, that holds a nil pointerCompare the pointer before it goes into the interface

FAQ​

What does fmt.Println print for a nil pointer?​

<nil>. For var plan *Plan, fmt.Println(plan) printed <nil>.

Why is an any holding a nil pointer not nil?​

An interface value holds a type and a value. The Go FAQ, Why is my nil error value not equal to nil?: "An interface value is nil only if the V and T are both unset". A nil *Plan stored in an any has the type *Plan, so the any isn't nil, although the pointer inside it is.

When should I use a pointer for an optional value?​

When "no value" must differ from an empty one. A *Plan can be nil, meaning no plan, while a Plan struct always holds a plan, even if its fields are empty.

Conclusion​

A pointer that was never set is nil, and reading a field through it panics. Check == nil first and return early, put the nil check on the left of && when you combine it with a field, and compare the pointer itself rather than an interface that holds it.

Additional Resources​