nil Pointers
The Zero Value of a Pointer
A pointer variable that's declared but never assigned an address automatically has the value nil, Go's way of representing 'points to nothing'.
Example: The Zero Value of a Pointer
package main
import "fmt"
func main() {
var p *int
fmt.Println("p is nil:", p == nil)
}
Login to try C/C++/Java/PHP code in the editor
Checking Before Dereferencing
Because dereferencing a nil pointer panics, code that might receive a nil pointer should check for it explicitly with an if statement before using *p.
Note: Get in the habit of nil-checking any pointer that came from a lookup, optional field, or function that could fail.
Example: Checking Before Dereferencing
package main
import "fmt"
func describe(p *string) string {
if p == nil {
return "no value"
}
return *p
}
func main() {
var name *string
fmt.Println(describe(name))
s := "Go"
fmt.Println(describe(&s))
}
Login to try C/C++/Java/PHP code in the editor
Nil Pointers in Structs
A struct field that's itself a pointer type defaults to nil when the struct is created without setting it, which is useful for representing optional data -- but it must be checked before dereferencing, just like any other pointer.
Example: Nil Pointers in Structs
package main
import "fmt"
type Profile struct {
Nickname *string
}
func main() {
p := Profile{}
if p.Nickname == nil {
fmt.Println("no nickname set")
}
}
Login to try C/C++/Java/PHP code in the editor
- Dereferencing a pointer without first checking it for nil, causing a runtime panic in production.
- Comparing a nil *T stored inside an interface value to nil directly and being surprised the interface itself is not nil.
- Forgetting struct pointer fields default to nil, not an empty struct, and must be checked before use.
- The zero value of any pointer type is nil, meaning it points to nothing.
- Dereferencing a nil pointer causes an immediate runtime panic.
- Comparing a pointer to nil with == is the standard way to check whether it's been set.
- A non-nil interface can still wrap a nil concrete pointer -- a classic Go gotcha worth knowing about.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: