~/The Nil Interface in Go Explained

Jan 15, 2025


The nil interface in Go refers to an interface value that has no type and no value stored. This is different from an interface value that holds a typed nil, such as a nil pointer.

A variable of interface type has two components: a dynamic type and a dynamic value. Both are nil when the interface is unassigned.

Example:

1
2
var x interface{}
fmt.Println(x == nil) // true

If you assign a nil pointer to an interface, it is not the same as the zero-value nil interface. The interface holds a type and a nil value:

1
2
3
var p *int = nil
var y interface{} = p
fmt.Println(y == nil) // false

Here, y has a dynamic type *int and a dynamic value nil.

This distinction is key for functions that return interface types: you must return a nil interface, not a typed nil, to indicate a true absence of value. Learn more in the Go FAQ.

Always check both the type and value stored in your interface variables. For advanced info, see Go blog on nil.

Tags: [go] [interface]