Empty Interfaces — Find the Bug¶
Bug 1 — nil any vs nil concrete¶
func ret() any {
var p *int = nil
return p
}
i := ret()
if i == nil { fmt.Println("nil") } else { fmt.Println("not nil") }
not nil. Interface (type: int, value: nil). Fix:* Bug 2 — Type assertion panic¶
Bug: Panic. Fix:s, ok := i.(string); if !ok { ... }. Bug 3 — Comparison panic¶
Bug: Panic — slice not comparable. Fix:reflect.DeepEqual(i, j) or specific equality. Bug 4 — Map[string]any boxing¶
m := map[string]any{}
for i := 0; i < 1e6; i++ {
m[fmt.Sprintf("k%d", i)] = i // each i goes to the heap
}
map[string]int{}, or generics if needed. Bug 5 — JSON number → float64¶
var data any
json.Unmarshal([]byte(`{"age": 30}`), &data)
m := data.(map[string]any)
age := m["age"].(int) // panic
float64. Fix: m["age"].(float64) or use a struct. Bug 6 — Variadic any forwarding¶
Bug:fmt.Println(args) — args is the entire slice. To forward: Fix: fmt.Println(args...). Bug 7 — interface{}{...} literal style issue¶
Not a bug, but style: Go 1.18+ — any is preferred: Bug 8 — Reflect on nil¶
Bug: Output<nil> (nil type). Fix: Bug 9 — Type switch has no fallthrough¶
switch v := i.(type) {
case int:
fmt.Println("int:", v)
fallthrough // ?
case string:
fmt.Println("string:", v)
}
fallthrough does not work in type switch (compile error). Fix: Write multi-case or separate logic per case. Bug 10 — any lookup expensive¶
type Lookup struct{ data map[any]any }
l := &Lookup{data: map[any]any{}}
for i := 0; i < 1e6; i++ {
if l.data[i] != nil { ... }
}
map[int]int. In this topic
Modes