Go

What does this print? (nil checks inside generic code)

Question 122HardGo 1.22 to 1.25
func IsNil[T any](v T) bool {
    return any(v) == nil
}

func main() {
    var p *int
    var err error
    fmt.Println(IsNil(p), IsNil[any](nil), IsNil(err), IsNil[error](nil))
}

Output: false true true true

  • IsNil(p): T is *int. Converting a nil *int to any produces a non-nil interface whose dynamic type is *int and whose value is nil. It is the classic typed-nil trap, so the result is false.
  • IsNil[any](nil): v is already a nil interface, so converting it to any keeps it nil. The result is true.
  • IsNil(err): T is error and err is a nil interface. Converting one nil interface to another interface type gives nil, so the result is true.
  • IsNil[error](nil): T is error and v is a nil error, so any(v) is nil. The result is true.

Note that you cannot write v == nil directly for T any. It fails with "mismatched types T and untyped nil" because nil is not valid for every type in the set. It compiles only when every type in the constraint is nilable, for example [T ~*int | ~[]int]. Interviewers use this question to test typed-nil understanding together with generics.

More on Generics

All 36 Generics questions