Interface in golang with an example

In Go, an interface defines a set of method signatures. Any type that implements all the methods of an interface is said to satisfy that interface. Here’s a simple example:

package main

import "fmt"

// Defining an interface
type Shape interface {
    Area() float64
}

// Implementing the interface for a rectangle
type Rectangle struct {
    Width  float64
    Height float64
}

// Area method for Rectangle
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// Implementing the interface for a circle
type Circle struct {
    Radius float64
}

// Area method for Circle
func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

func main() {
    // Creating instances of Rectangle and Circle
    rectangle := Rectangle{Width: 5, Height: 10}
    circle := Circle{Radius: 7}

    // Calling the Area method through the Shape interface
    printArea(rectangle)
    printArea(circle)
}

// Function that takes any type implementing the Shape interface
func printArea(shape Shape) {
    fmt.Printf("Area: %0.2f\n", shape.Area())
}

In this example:

  • We define the Shape interface with a single method Area.
  • We create two types: Rectangle and Circle, each implementing the Area method.
  • The printArea function accepts any type that implements the Shape interface.
  • In the main function, we create instances of Rectangle and Circle and pass them to printArea.

This example demonstrates polymorphism in Go. Both Rectangle and Circle can be treated as a Shape because they implement the Area method. The printArea function can work with any type that satisfies the Shape interface.

You can extend this example by adding more shapes or methods to the Shape interface to see how different types can implement the same interface.

Leave a Reply

Your email address will not be published. Required fields are marked *