Home
Search
Golang Interface ExampleUse an interface with a method. Implement the method and pass a struct as an interface.
dot net perls
Interface. In Golang, 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.
Sort
An example. This program implements an interface. The "type Page" is an interface that requires one method: Print. And HtmlPage implements Page.
Note An interface can be implemented by specifying all the required methods, or it can just use a name (like Page within HtmlPage here).
Main This creates a new instance of the HtmlPage struct, which is a type that implements Page.
Display This func receives any variable that implements Page. So we can just pass an HtmlPage to it.
Print Finally the Print method is invoked through the Page interface. It uses the HtmlPage implementation.
Golang program that uses interface
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.
An abstraction. 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.
A summary. 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.
Home
© 2007-2021 sam allen. see site info on the changelog