Recognize nil pointer errors
Recognize nil pointer errors
The zero value of a pointer type is nil. A nil pointer does not refer to a variable. Dereferencing it causes a runtime panic. Test for nil before reading or writing through a pointer whenever absence is allowed by the function contract.
package main
import ( "fmt")
func main() { var p *int fmt.Println(p == nil) x := 0 p = &x fmt.Println(p == nil, *p)}A pointer to an integer containing zero is not nil. Check the pointer itself, not the value obtained by dereferencing it. Evaluating *p to test for zero would already fail if p were nil.
Expected output:
truefalse 0Represent an optional value
package main
import ( "fmt")
func valueOr(p *int, fallback int) int { if p == nil { return fallback } return *p}func main() { x := 0 fmt.Println(valueOr(nil, 10)) fmt.Println(valueOr(&x, 10))}The function distinguishes absence from a present zero. For mandatory pointer arguments, document the non-nil requirement. For optional arguments, define the fallback explicitly. Do not silently substitute zero if zero is meaningful.
Expected output:
100Try it locally
Implement read(p *int) (int,bool). Return 0,false for nil and *p,true otherwise. Print results for nil and a pointer to zero.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pointers and ownership 02: Recognize nil pointer errors
Check the lesson objective before moving on.
What happens when *p is evaluated for a nil *int?
Which test distinguishes absence from a present zero?