go-nil-pointer
Pointer receiver nil safety - methods can be called on nil
When & Why to Use This Skill
This Claude skill provides a specialized pattern for Go (Golang) developers to implement nil-safe pointer receivers. It addresses the common 'nil pointer dereference' panic by teaching how to handle nil receivers within methods, ensuring code robustness and enabling elegant recursive data structure traversals.
Use Cases
- Recursive Data Structures: Implementing methods on trees or linked lists where a nil pointer naturally represents an empty node or base case.
- Robust API Design: Creating defensive methods that return default values or 'zero' behaviors instead of crashing when called on uninitialized pointers.
- Code Quality Audits: Identifying and refactoring fragile Go code where methods assume non-nil receivers, thereby reducing runtime panics.
- Optional Configuration Handling: Managing optional struct fields where a nil pointer signifies a default state that still requires method-based logic.
| name | go-nil-pointer |
|---|---|
| description | Pointer receiver nil safety - methods can be called on nil |
Pointer Receiver Nil
Problem
Methods with pointer receivers can be called on nil. Must handle nil receiver.
Pattern
WRONG - Assume receiver is non-nil
type Tree struct {
Value int
Left *Tree
}
func (t *Tree) Sum() int {
return t.Value + t.Left.Sum() // PANIC if t or t.Left is nil
}
CORRECT - Handle nil receiver
type Tree struct {
Value int
Left *Tree
Right *Tree
}
func (t *Tree) Sum() int {
if t == nil {
return 0 // Nil tree has sum of 0
}
return t.Value + t.Left.Sum() + t.Right.Sum()
}
// Now safe to call
var tree *Tree // nil
sum := tree.Sum() // Returns 0, no panic
Use Cases
Nil receiver pattern enables elegant recursive algorithms and optional behavior.
Quick Fix
- Check if receiver is nil at method start
- Define sensible zero behavior for nil receiver
- Document whether methods are nil-safe
When NOT to Use
If nil receiver doesn't make semantic sense, panic early with clear message.