Sobes.tech
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{} — variable x of an empty interface type, which by default is equal to nil, meaning it contains neither type nor value.
  • But if you assign some value to x, for example x = 5, then x is no longer nil, as it contains the type int and the value 5.

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.

What is the difference between an empty interface… - sobes.tech