Golang interfaces

From wikinotes
Revision as of 03:14, 6 June 2022 by Will (talk | contribs) (Created page with "Similar to other languages, interfaces in go define a contract of method-signatures that implementors must have.<br> Unlike other languages, golang interfaces are implicit --...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

Basics

// 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"))