Go Interfaces
An interface lists methods. Any type that has those methods satisfies it automatically: there is no implements keyword.
ExampleGo
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
}
type Circle struct{ R float64 }
type Rect struct{ W, H float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (r Rect) Area() float64 { return r.W * r.H }
func main() {
shapes := []Shape{Circle{1}, Rect{2, 3}}
for _, s := range shapes {
fmt.Printf("%.2f\n", s.Area())
}
}Output
3.14 6.00
Quick check
How does a Go type satisfy an interface?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.