How is polymorphism implemented in Golang interfaces?

In the Go language, interfaces allow for polymorphism, where different types can exhibit the same behavior.

To achieve polymorphism, you need to define an interface and implement it in different types. Then you can invoke the methods of the interface by using variables of the interface type, thus achieving polymorphism.

Here is a way to achieve polymorphism:

  1. Define an interface: First, it is necessary to define an interface and declare the methods that need to be implemented within the interface.
type Shape interface {
    Area() float64
    Perimeter() float64
}
  1. Implement the interface: Implement the interface in different types and provide specific implementations for the methods.
type Rect struct {
    width  float64
    height float64
}

func (r Rect) Area() float64 {
    return r.width * r.height
}

func (r Rect) Perimeter() float64 {
    return 2 * (r.width + r.height)
}

type Circle struct {
    radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.radius * c.radius
}

func (c Circle) Perimeter() float64 {
    return 2 * math.Pi * c.radius
}
  1. Utilizing polymorphism: calling methods that implemented an interface through variables of interface type.
func printShapeInfo(s Shape) {
    fmt.Println("Area:", s.Area())
    fmt.Println("Perimeter:", s.Perimeter())
}

func main() {
    rect := Rect{width: 5, height: 3}
    circle := Circle{radius: 2}

    printShapeInfo(rect)
    printShapeInfo(circle)
}

In the example above, the Shape interface defines two methods, Area() and Perimeter(). Then, the Rect and Circle structures each implement the Shape interface and provide the specific implementations of these two methods.

In the main function, we created a variable of type Rect named rect and a variable of type Circle named circle. We then called the printShapeInfo function, passing in rect and circle to achieve polymorphism. The parameter type in the printShapeInfo function is the Shape interface, so it can accept any type that implements the Shape interface and call the corresponding methods.

In the end, the output shows the combined area and perimeter of Rect and Circle. This demonstrates polymorphism being achieved through interfaces, where different types of variables can exhibit similar behavior.

bannerAds