go-nil-interface

Interface nil trap - typed nil is not nil

⭐2stars🔀0forks📁View on GitHub🕐Updated Dec 28, 2025

When & Why to Use This Skill

This Claude skill helps developers identify and resolve the 'interface nil trap' in Go (Golang). It explains the critical distinction between a typed nil pointer and a nil interface, providing clear 'wrong vs. correct' code patterns to prevent subtle logic bugs in error handling and interface assignments.

Use Cases

  • Case 1: Debugging Go applications where an 'if err != nil' check unexpectedly passes despite no error occurring.
  • Case 2: Conducting code reviews to ensure functions return untyped nil instead of typed nil variables, adhering to Go best practices.
  • Case 3: Educating developers on the internal (type, value) structure of Go interfaces to prevent common memory and logic pitfalls.
namego-nil-interface
descriptionInterface nil trap - typed nil is not nil

Interface Nil Trap

Problem

A typed nil pointer stored in an interface is NOT nil.

Pattern

WRONG - Typed nil escapes

func GetUser(id int) error {
    var err *MyError  // typed nil
    if id < 0 {
        err = &MyError{"invalid id"}
    }
    return err  // Returns non-nil interface containing nil pointer!
}

if err := GetUser(1); err != nil {
    // This branch RUNS even though no error occurred
    fmt.Println("error:", err)
}

CORRECT - Return untyped nil

func GetUser(id int) error {
    if id < 0 {
        return &MyError{"invalid id"}
    }
    return nil  // Return untyped nil
}

if err := GetUser(1); err != nil {
    // This branch does NOT run
    fmt.Println("error:", err)
}

Why It Happens

Interface contains (type, value). Typed nil has (type=*MyError, value=nil). This is different from (type=nil, value=nil).

Quick Fix

  • Return nil directly, not typed nil variable
  • Or return concrete type, not interface