Interface in Golang

(5 minutes for reading)

Basic using

When we have many struct which have many same methods(same name, same params, same returned result), we call them having same interface. So hard to understand, right? We will explain by example

I have 2 structs, circle and rectangle. Although circle has radius and rectangle has width & height, both of them still have area method to get area of them, but in different function. So, we declare a interface for them geometry

Here’s a basic interface for geometric shapes.

After that, I declare for struct circle and rectangle which contain method area but in different ways

Here, because circle and rectangle implement all functions of interface geometry

type geometry interface {
    area() float64 // common func of interface
}

type rect struct {
    width, height float64
}
func (r rect) area() float64 {
    return r.width * r.height
}

type circle struct {
    radius float64
}
func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}

Now, how to use?

If a variable has an interface type, then we can call methods that are in the named interface. Here’s a generic getArea function taking advantage of this to work on any geometry.

The circle and rectangle struct types both implement the geometry interface so we can use instances of these structs as arguments to measure.

func getArea(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
}
func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}

    getArea(r)
    getArea(c)
}

Other Using

I can say, interface present for any struct or data type you want. You will understand after reading this example

I want init an slice, but I don’t want to set data type for each element before. How to do that?

With this way, arrayInterface variable can contain any data type, struct, interface, …

arrayInterface := make([]interface{}, 0)

arrayInterface = append(arrayInterface, 1)

arrayInterface = append(arrayInterface, "2")

arrayInterface = append(arrayInterface, rect{width: 3, height: 4})

fmt.Println(arrayInterface)

The same with map

mapInterface := make(map[string]interface)

mapInterface["k1"] = 1
mapInterface["k2"] = "2"
mapInterface["k3"] = circle{radius: 5}

fmt.Println(arrayInterface)

Interface is really strong in Golang, you can read more on

View on github

PreNext