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: