Junior — Middle
What is the difference between an empty interface expression and a nil value in Go?
sobes.tech AI
Answer from AI
In Go language, an empty interface (interface{}) is a type that can hold a value of any type, including nil. However, the expression of an empty interface and the value nil are different things.
var x interface{}— variablexof an empty interface type, which by default is equal tonil, meaning it contains neither type nor value.- But if you assign some value to
x, for examplex = 5, thenxis no longernil, as it contains the typeintand the value5.
The difference is that in Go, an interface internally is represented by two pointers: one to the type and one to the value. An interface equals nil only if both pointers are nil.
Example:
var i interface{} // i == nil
var p *int = nil
i = p // i != nil, because the type *int is present, even though the value is nil
fmt.Println(i == nil) // false
Thus, an empty interface can contain a value of nil of a specific type, but the interface itself will not be equal to nil. This is an important point when checking for nil in Go.