Go: Understand the Empty Interface
--
An empty interface can be used to hold any data and it can be a useful parameter since it can work with any type. To understand how an empty interface works and how it can hold any type, we should first understand the concept behind the name.
Interfaces
Here is a good definition of the empty interface by Jordan Oreilli:
An interface is two things: it is a set of methods, but it is also a type.
Theinterface{}
type is the interface that has no methods. Since there is noimplements
keyword, all types implement at least zero methods, and satisfying an interface is done automatically, all types satisfy the empty interface
A method with an empty interface as argument can therefore accept any type. Go will proceed to a conversion to an interface type to serve this function.
Russ Cox made a great article about the internal representation of the interfaces and explains that an interface is composed of two words:
- a pointer to information about the type stored
- a pointer to the associated data
Here is a representation by Russ in 2009 when runtime was written in C:
The runtime is now written in Go but the representation is still the same. We can verify that with printing the empty interface:
(0x10591e0,0x10be5c6)
Both addresses represent the two pointers to type information and the value.
Underlying structure
The underlying representation of the empty interface is documented in the reflection package:
type emptyInterface struct {
typ *rtype // word 1 with type description
word unsafe.Pointer // word 2 with the value
}