4. Nil Pointers
The Danger
var p *int // p is nil (points to nothing)
fmt.Println(*p) // β PANIC! Can't dereference nilAlways Check for Nil
var p *int
if p != nil {
fmt.Println(*p) // β Safe to dereference
} else {
fmt.Println("Pointer is nil")
}Real Example
type user struct {
name string
age int
}
func updateAge(u *user, newAge int) {
if u == nil {
fmt.Println("Cannot update nil user")
return
}
u.age = newAge // Safe to use
}
func main() {
var bob *user // bob is nil
updateAge(bob, 30) // Without check, this would panic
}Common Pattern
Why Pointers Can Be Nil
Safe vs Unsafe
Checking Nil in Your Code
Key Takeaways
Quick Reference
Action
Code
Safe?