What is a nil interface? What is under the hood?
sobes.tech AI
Answer from AI
In Go, an interface is a type that describes a set of methods. An interface can have a nil value, but it is important to understand that a nil interface is an interface that has neither a value nor a type.
Under the hood, an interface in Go is represented by a structure with two fields:
- type — points to the specific type of the value that implements the interface
- data pointer — points to the specific value
When an interface is nil, both fields — type and data — are nil. However, if the interface contains a value, but the value itself is nil (for example, a pointer inside the interface is nil), then the type will not be nil, but the data will be nil.
This leads to a common mistake:
var p *int = nil
var i interface{} = p
fmt.Println(i == nil) // false, because the type *int is not nil, even though the value is nil
Thus, a nil interface is an interface that has neither a type nor a value. If at least the type is present, the interface is not equal to nil, even if the value inside is nil.
It is important to consider this when checking for nil to avoid unexpected bugs.