Interfaces

  • Interfaces are named collections of method signatures

//Here's a basic interface for geometric shapes.
type geometry interface {
    area() float64
    perim() float64
}

type rect struct {
    width, height float64
}

type circle struce {
    radius float64
}

func (r rect) area() float64 {
    return r.width * r.height
}
func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}

func (c circle) area() float64 {
	return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
	return 2 * math.Pi * c.radius
}
  • To implement an interface in Go, we just need to implement all the methods

Last updated