Home
Map
interface ExampleUse an interface with a method. Implement the method and pass a struct as an interface.
Go
This page was last reviewed on Feb 19, 2023.
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 Slice
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 19, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.