Types that share the same methods

A rectangle and a circle are different types, but both have an area. Say you want one slice that holds both, and one loop that adds up their areas. A slice can only hold one type, so neither []Rect nor []Circle works. Go solves this with an interface: a type that lists methods. Any value that has those methods can be stored in it.

package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
}

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
}

func main() {
	shapes := []Shape{
		Rect{Width: 3, Height: 4},
		Circle{Radius: 1},
		Rect{Width: 2, Height: 2},
	}
	total := 0.0
	for _, s := range shapes {
		fmt.Printf("%.2f\n", s.Area())
		total += s.Area()
	}
	fmt.Printf("Total: %.2f\n", total)
}

Output:

12.00
3.14
4.00
Total: 19.14

The program imports math for math.Pi, the number pi that the circle's area needs.

type Shape interface { Area() float64 } says: a Shape is anything that has a method Area with no parameters that returns a float64. Rect has one, and so does Circle, so both are shapes. The slice []Shape can hold both.

When the loop calls s.Area(), Go looks at the real value inside s and runs its method. For the first item that is Rect's Area, and for the second it is Circle's.

No "implements" needed

Notice that Rect never says it is a Shape. In Go, a type fits an interface just by having the right methods. You never write that it does. This means you can add a new shape later, give it an Area method, and put it in the same slice. The loop does not change at all.

If a type is missing a method, Go tells you before the program runs. Here Square has no Area method:

package main

import "fmt"

type Shape interface {
	Area() float64
}

type Square struct {
	Side float64
}

func main() {
	var s Shape = Square{Side: 2}
	fmt.Println(s)
}

Output:

# command-line-arguments
./main.go:14:16: cannot use Square{…} (value of type Square) as Shape value in variable declaration: Square does not implement Shape (missing method Area)

var s Shape declares a variable of an interface type. It can hold any value that has the methods of Shape, but Square does not, so the program is rejected at line 14.

Why interfaces help

A function with an interface parameter works with every type that fits, even types written after the function. Here printArea takes a Shape, and Square now has the Area method it was missing:

package main

import "fmt"

type Shape interface {
	Area() float64
}

func printArea(s Shape) {
	fmt.Printf("%.2f\n", s.Area())
}

type Rect struct {
	Width, Height float64
}

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

type Square struct {
	Side float64
}

func (s Square) Area() float64 {
	return s.Side * s.Side
}

func main() {
	printArea(Rect{Width: 3, Height: 4})
	printArea(Square{Side: 2})
}

Output:

12.00
4.00

printArea only cares that it can call Area. It does not care whether it gets a rectangle, a square, or something else. Good Go interfaces are small, often with just one method, because a small interface is easy for many types to fit.

A struct does not even need fields to fit an interface. type Cash struct{} is a struct with no fields, and it fits an interface as soon as it has the right methods.

In the exercise, write the method of the Charger interface, then write a Charge method for Cash so it fits the interface too.