Go by Example : Interfaces

Interfaces in Go are used to define a set of methods that a type must implement. A type that implements all the methods defined by an interface is said to implement that interface.

Here’s a simple example that demonstrates how interfaces can be used in Go:

package main

import "fmt"

type Shape interface {
    Area() float64
}

type Rectangle struct {
    width, height float64
}

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

type Circle struct {
    radius float64
}

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

func main() {
    r := Rectangle{width: 10, height: 5}
    c := Circle{radius: 5}

    shapes := []Shape{r, c}
    for _, shape := range shapes {
        fmt.Println("Shape area:", shape.Area())
    }
}

In this example, we define a Shape interface with a single method, Area. We then define two structs, Rectangle and Circle, that both implement the Area method.

In the main function, we create instances of both Rectangle and Circle, and store them in a slice of Shapes. We then loop over the slice, printing the area of each shape.

The output of this program will be:

Shape area: 50
Shape area: 78.53975

Here’s another example that demonstrates the use of interfaces in Go:

package main

import "fmt"

type Animal interface {
    Speak() string
}

type Dog struct {}

func (d Dog) Speak() string {
    return "Woof!"
}

type Cat struct {}

func (c Cat) Speak() string {
    return "Meow!"
}

func main() {
    animals := []Animal{Dog{}, Cat{}}
    for _, animal := range animals {
        fmt.Println(animal.Speak())
    }
}

In this example, we define an Animal interface with a single method, Speak. We then define two structs, Dog and Cat, that both implement the Speak method.

In the main function, we create instances of both Dog and Cat, and store them in a slice of Animals. We then loop over the slice, calling the Speak method of each animal and printing the result.

The output of this program will be:

Woof!
Meow!

As you can see, by using interfaces, we can write code that works with multiple types in a flexible and generic way. Interfaces provide a way to define a common set of behaviors for different types, and allow you to write code that can work with any type that implements those behaviors.


Comments

Leave a Reply

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