I've read through the Effective Go and Go Tutorials as well as some source, but the exact mechanism behind the interface {}
syntax is Go is somewhat mysterious to me. I first saw it when trying to implement heap.Interface
and it seems to be a container of some kind (reminds me of a monad a little) from which I can extract values of arbitrary type.
Why is Go written to use this? Is it some kind of workaround for generics? Is there a more elegant way to get values from a heap.Interface
than having to dereference them with heap.Pop(&h).(*Foo)
(in the case of a heap pointers to type Foo)?
interface{}
is a generic box that can hold everything. Interfaces in go define a set of methods, and any type which implements these methods conforms to the interface. interface{}
defines no methods, and so by definition, every single type conforms to this interface and therefore can be held in a value of type interface{}
.
It's not really like generics at all. Instead, it's a way to relax the type system and say "any value at all can be passed here". The equivalent in C for this functionality is a void *
pointer, except in Go you can query the type of the value that's being held.
Here is an excellent blog post that explains what is going on under the hood.