Junior — Middle
What is the difference between an empty interface and an interface with a nil value in Go?
sobes.tech AI
Answer from AI
In Go, the empty interface interface{} is an interface that contains no methods and can hold a value of any type. However, when a variable of interface type contains nil, it is important to understand what exactly nil means.
- Empty interface with no value: a variable of interface type that does not point to any value is considered nil.
- Interface with a nil value: if the interface contains a specific type, but the value of that type is nil, then the interface itself is not equal to nil because it contains type information.
Example:
var i interface{} // i == nil
var p *int = nil // p == nil
i = p // i != nil, because it contains type *int, but the value is nil
fmt.Println(i == nil) // false
fmt.Println(p == nil) // true
This is important to consider when checking for nil to avoid unexpected errors.