In Go, an interface
contains a method set. Every type that has an interface
's methods automatically implements that interface
.
With interfaces, we can unify code that uses diverse types. A func
can act on the interface
, not the many structs that might implement those methods.
This program implements an interface
. The "type Page" is an interface
that requires one method: Print. And HtmlPage
implements Page.
interface
can be implemented by specifying all the required methods, or it can just use a name (like Page within HtmlPage
here).Main
creates a new instance of the HtmlPage
struct
, which is a type that implements Page.Display()
receives any variable that implements Page. So we can just pass an HtmlPage
to it.interface
. It uses the HtmlPage
implementation.package main import "fmt" type Page interface { Print(value int) } type HtmlPage struct { // Implement the Page interface. Page } func (h *HtmlPage) Print(value int) { // Implement Print for HtmlPage struct. fmt.Printf("HTML %v", value) fmt.Println() } func display(p Page) { // Call Print from Page interface. // ... This uses the HtmlPage implementation. p.Print(5) } func main() { // Create an HtmlPage instance. p := new(HtmlPage) display(p) }HTML 5
Result
The above interface
example program ends up invoking the Print()
method. It prints HTML 5 because the int
argument specified is 5.
Interfaces allow us to create an abstraction upon existing types. The Page abstraction above could be used on many different page structs, not just HtmlPage
.
Interfaces in Go are powerful. With them we gain a way to write code that acts upon many structs at once. This unifies and improves programs.