Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the role of the "interface {}" syntax in Go?

Tags:

interface

go

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)?

like image 501
R. P. Dillon Avatar asked Feb 08 '11 22:02

R. P. Dillon


2 Answers

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.

like image 193
Lily Ballard Avatar answered Sep 30 '22 04:09

Lily Ballard


Here is an excellent blog post that explains what is going on under the hood.

like image 26
rog Avatar answered Sep 30 '22 03:09

rog