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).
Start Main creates a new instance of the HtmlPage struct, which is a type that implements Page.
Info Display() receives any variable that implements Page. So we can just pass an HtmlPage to it.
Finally The Print method is invoked through the Page 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.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 19, 2023 (edit).