I love using Go’s interface feature to declaratively define my public API structure. Consider this example:
package main
import (
"fmt"
)
// Declare the interface.
type Geometry interface {
area() float64
perim() float64
}
// Struct that represents a rectangle.
type rect struct {
width, height float64
}
// Method to calculate the area of a rectangle instance.
func (r *rect) area() float64 {
return r.width * r.height
}
// Method to calculate the perimeter of a rectange instance.
func (r *rect) perim() float64 {
return 2 * (r.width + r.height)
}
// Notice that we're calling the methods on the interface,
// not on the instance of the Rectangle struct directly.
func measure(g Geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
func main() {
r := &rect{width: 3, height: 4}
measure(r)
}
You can play around with the example on Go Playground. Running it will print: