C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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)
}
Output
HTML 5