Interface embedding another interface in Go Programming Language
Interfaces may embed other interfaces, this behavior is an aspect of interface polymorphism which is known as ad hoc polymorphism.
When one type is embedded into another type, the methods of the embedded type are available to the embedding type. The method or methods of the embedded interface are accessible to the embedding interface.
Example
package main
import "fmt"
type Geometry interface {
Edges() int
}
type Polygons interface {
Geometry // Interface embedding another interface
}
type Pentagon int
type Hexagon int
type Octagon int
type Decagon int
func (p Pentagon) Edges() int { return 5 }
func (h Hexagon) Edges() int { return 6 }
func (o Octagon) Edges() int { return 8 }
func (d Decagon) Edges() int { return 10 }
func main() {
p := new(Pentagon)
h := new(Hexagon)
o := new(Octagon)
d := new(Decagon)
polygons := [...]Polygons{p, h, o, d}
for i := range polygons {
fmt.Println(polygons[i].Edges())
}
}
Most Helpful This Week
How to declare Interface Type in Go Programming Language
Polymorphism in Go Programming Language
Interfaces with similar methods in Go Programming Language
Defining a type that satisfies an interface in Go Programming Language
Interface Accepting Address of the Variable in Golang
Empty Interface Type in Go Programming Language
Implementing Multiple Interfaces in Go Programming Language