Empty interface

Since every type satisfies the empty interface: interface{} we can createa generic function which has an empty interface as its argument:

  1. func g(something interface{}) int {
  2. return something.(I).Get()
  3. }

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.

  1. s = new(S)
  2. 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:

  1. var i int
  2. 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.