4. Nil Pointers

Pointers can be very dangerous.

If a pointer points to nothing (the zero value of the pointer type is nil) then dereferencing it will cause a runtime error (a panicarrow-up-right) that crashes the program. Generally speaking, whenever you're dealing with pointers you should check if it's nil before trying to dereference it.

The Danger

Dereferencing a nil pointer causes a panic (runtime crash):

var p *int           // p is nil (points to nothing)
fmt.Println(*p)      // ❌ PANIC! Can't dereference nil

Always 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

Unsafe (will panic):

Safe:

Checking Nil in Your Code

Key Takeaways

  1. Nil pointer = pointer that doesn't point to anything

  2. Dereferencing nil = runtime panic (crash)

  3. Always check if ptr != nil before using

  4. Check early at the start of functions

  5. Return early if nil to avoid crashes

Quick Reference

Action
Code
Safe?

Declare pointer

var p *int

βœ“ (just nil)

Check if nil

if p == nil

βœ“ Safe check

Dereference without check

*p = 5

❌ Panic if nil

Dereference with check

if p != nil { *p = 5 }

βœ“ Safe

Access field without check

p.field

❌ Panic if nil

Access field with check

if p != nil { p.field }

βœ“ Safe

Rule: When working with pointers, always ask "Could this be nil?" If yes, check before using.

Assignment

Let's make our profanity checker safe. Update the removeProfanity function. If message is nil, return early to avoid a panicarrow-up-right. After all, there are no bad words to remove.

Solution