Golang interfaces

From wikinotes
Revision as of 14:38, 6 June 2022 by Will (talk | contribs)

Similar to other languages, interfaces in go define a contract of method-signatures that implementors must have.
Unlike other languages, golang interfaces are implicit -- an object with all of the required methods automatically satisfies an interface.

Similar to other languages, a param can be typed to accept an interface, which abstracts the actual type that is received.

Basics

In go, many interfaces expose just a single method, and are named after the method they expose.
Frequently, interfaces are implemented on structs (but they can be for any type).

// declare an interface
type Writer interface {
    Write([]byte) (int, error)
}
// implement an interface (automatic if methods match)
type PrinterWriter struct {}

func (w PrinterWriter) Write(data []byte) (int, error) {
    // ...
}
var w Writer = PrinterWriter{}  // <-- type 'Writer'
w.Write([]byte("Foobar"))

Libraries do not need to expose interfaces in go, you can create them for the subset of methods that are useful to you.

Embedding

Like structs, interfaces can be embedded.

type Walker interface {
    Walk nil
}

type BubblegumChewer interface {
    ChewGum nil
}

// includes all methods from previous two interfaces
type BubblegumChewingWalker interface {
    Walker
    BubblegumChewer
}