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*inttoanyproduces a non-nil interface whose dynamic type is*intand 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 toanykeeps it nil. The result is true.IsNil(err): T iserrorand err is a nil interface. Converting one nil interface to another interface type gives nil, so the result is true.IsNil[error](nil): T iserrorand v is a nil error, soany(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
- Q120Can you store a generic function in a variable or pass it around without instantiating it?
- Q121How do you get and check the zero value of a type parameter
T? - Q123What does this print? (type switch on a type parameter)
- Q124Why doesn't Go allow type parameters on methods? What do you do instead?
- Q125How do you write methods on a generic type? What is wrong with
func (s Stack[int]) Sum() int? - Q126Name the restrictions around type parameters: embedding, type declarations, and method sets.