How to use interfaces and implement polymorphism in Go?

In Go, interfaces are used to define a contract that a type must satisfy by implementing all the methods defined in the interface. Polymorphism is achieved in Go by using interfaces, which allow different types to be used interchangeably if they satisfy a common interface. Here's how you can use interfaces and implement polymorphism in Go:

Step 1: Create an interface

type Shape interface { Area() float64 Perimeter() float64 }

Step 2: Implement the interface for different types

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 } type Rectangle struct { length, width float64 } func (r Rectangle) Area() float64 { return r.length * r.width } func (r Rectangle) Perimeter() float64 { return 2 * (r.length + r.width) }

Step 3: Use the interface and achieve polymorphism

func PrintShapeDetails(s Shape) { fmt.Printf("Area: %f\n", s.Area()) fmt.Printf("Perimeter: %f\n", s.Perimeter()) } func main() { var shape Shape shape = Circle{radius: 5} PrintShapeDetails(shape) shape = Rectangle{length: 4, width: 6} PrintShapeDetails(shape) }

In the above example, we define an interface called Shape that has two methods: Area and Perimeter. Then, we create two types, Circle and Rectangle, and implement the Shape interface for both types. Finally, we use the interface Shape to achieve polymorphism by passing different types to the PrintShapeDetails function. The function can accept any type that satisfies the Shape interface, allowing us to treat different shapes uniformly.