Go Interface

In Go, an interface is a collection of method signatures that define a set of behaviors. An interface specifies what methods a type must have, but does not provide any implementation details.

Here's an example of how to declare and use an interface in Go:

// Declare an interface with a single method signature
type Shape interface {
    Area() float64
}

// Define a struct for a rectangle
type Rectangle struct {
    width  float64
    height float64
}

// Define a method on the Rectangle struct that satisfies the Shape interface
func (r Rectangle) Area() float64 {
    return r.width * r.height
}

// Define a struct for a circle
type Circle struct {
    radius float64
}

// Define a method on the Circle struct that satisfies the Shape interface
func (c Circle) Area() float64 {
    return math.Pi * c.radius * c.radius
}

func main() {
    // Declare a slice of Shape interface values that can hold both Rectangle and Circle structs
    shapes := []Shape{
        Rectangle{width: 5, height: 3},
        Circle{radius: 2},
    }

    // Loop through the slice of shapes and print the area of each one
    for _, shape := range shapes {
        fmt.Println("Area =", shape.Area())
    }
}
S‮o‬urce:www.theitroad.com

In this example, an interface Shape is defined with a single method signature for Area() that returns a float64. Two structs Rectangle and Circle are defined, each with a method that satisfies the Shape interface.

In the main function, a slice of Shape interface values is declared, and two instances of Rectangle and Circle structs are assigned to it. A loop then iterates over the slice and calls the Area() method for each shape, printing the result to the console.