Empty interface
Since every type satisfies the empty interface: interface{}
we can createa generic function which has an empty interface as its argument:
func g(something interface{}) int {
return something.(I).Get()
}
The return something.(I).Get()
is the tricky bit in this function. The valuesomething
has type interface{}
, meaning no guarantee of any methods at all:it could contain any type. The .(I)
is a type assertion which converts something
to an interface of type I
. If we have that type wecan invoke the Get()
function. So if we create a new variable of the typeS
, we can just call g()
, because S
also implements the empty interface.
s = new(S)
fmt.Println(g(s));
The call to g
will work fine and will print 0. If we however invoke g()
witha value that does not implement I
we have a problem:
var i int
fmt.Println(g(i))
This compiles, but when we run this we get slammed with: “panic: interfaceconversion: int is not main.I: missing method Get”.
Which is completely true, the built-in type int
does not have a Get()
method.