Go interface example

In this example, we show how to use the interface in Golang with an example.

An interface is a set of function signatures and it is a specific type. Another type implements an interface by implementing its functions. While languages like Java or C# explicitly implement interfaces, there is no explicit declaration of intent in Go.

Go interface example

The following example uses a simple Shape interface.


package main

import (
    "fmt"
    "math"
)

type Shape interface {
    Area() float64
}

type Rectangle struct {
    Width, Height float64
}

type Circle struct {
    Radius float64
}

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

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

func getArea(shape Shape) {

    fmt.Println(shape.Area())
}

func main() {

    r := Rectangle{Width: 7, Height: 8}
    c := Circle{Radius: 5}

    getArea(r)
    getArea(c)
}

Output:

56
78.53981633974483

Comments