typestar

The nil interface trap in Go

An interface holding a nil pointer is not itself nil.

type MyError struct{}

func (e *MyError) Error() string { return "my error" }

// broken returns a non-nil interface holding a nil pointer.
func broken(fail bool) error {
    var custom *MyError
    if fail {
        custom = &MyError{}
    }
    return custom
}

func fixed(fail bool) error {
    if fail {
        return &MyError{}
    }
    return nil
}

func compare() (bool, bool) {
    return broken(false) != nil, fixed(false) != nil
}

How it works

  1. The interface has a type and a value; only both nil is nil.
  2. Returning a typed nil error makes err != nil unexpectedly true.
  3. Return a bare nil, or check before wrapping.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
394
Tokens
90
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 54 seconds.

Type this snippet

Step 4 of 4 in Interfaces, step 7 of 19 in Interfaces & generics.

← Previous Next →