go-nil-slice
Slice zero-value behavior - nil slice is usable
When & Why to Use This Skill
This Claude skill provides comprehensive guidance on Go's slice zero-value behavior, explaining why nil slices are usable and how they differ from empty slices in operations like append and JSON encoding. It helps developers write more idiomatic and bug-free Go code by clarifying common misconceptions about slice initialization and memory management.
Use Cases
- Scenario 1: Debugging JSON API responses where 'null' is returned instead of '[]' due to specific slice initialization choices.
- Scenario 2: Optimizing Go code by leveraging nil slices for memory efficiency in uninitialized states without risking runtime panics.
- Scenario 3: Ensuring safe use of append, len, and range operations on uninitialized slices to maintain robust application logic.
- Scenario 4: Implementing idiomatic Go patterns during code reviews to clearly distinguish between 'no data' (nil) and 'empty data' (empty slice).
| name | go-nil-slice |
|---|---|
| description | Slice zero-value behavior - nil slice is usable |
Slice Zero-Value
Problem
Nil slices are valid and usable, but behavior differs from empty slices.
Pattern
CORRECT - Nil slice works with append
var s []int // nil slice
s = append(s, 1, 2, 3) // OK, creates new backing array
fmt.Println(s) // [1 2 3]
Nil vs Empty Slice
var nilSlice []int // nil slice
emptySlice := []int{} // empty slice (non-nil)
len(nilSlice) == 0 // true
len(emptySlice) == 0 // true
nilSlice == nil // true
emptySlice == nil // false
json.Marshal(nilSlice) // "null"
json.Marshal(emptySlice) // "[]"
When It Matters
// JSON encoding differs
type Response struct {
Items []string // Will encode as null if nil, [] if empty
}
Quick Fix
- Nil slices work with append, len, range
- Use nil for "no data", []T{} for "empty data"
- Check JSON encoding behavior if needed