home

Introduction To Golang: Interfaces

Jan 10, 2013

Go interfaces define behavior that a type must implement (and expose). A simple example is the io.Writer interface:

type Writer interface {
  Write(p []byte) (n int, err error)
}

There are two sides to this story. First, we can now write a function that expects a io.Writer argument and know that it'll expose a Write method which takes a byte array. You get nice compile-time checks and everything.

On the other side, we can now create our own writers and pass them to whatever function is expecting a Writer. The way Go does this is quite clever. In languages like Java, implementing an interface is explicit. In Go, the implementation is automatically inferred, at compile-time, by the methods attached to our type. In other words, the following is all we need to do to implement the Writer interface:

type Unicorn struct {

}
func (u *Unicorn) Write(p []byte) (n int, err error) {
  //do something
  return
}

Now, an instance of Unicorn is welcomed wherever an io.Writer is expected. No verbosity about it at all.

If we also want it to implement io.Closer, we simply attach a Close method:

func (u *Unicorn) Close() (err error) {
//do something
  return
}

It's worth noting that a number of interfaces in Go wrap a single method, which is actually quite convenient