Interfaces in Go
Implicit satisfaction: no implements keyword.
type Shape interface {
Area() float64
Name() string
}
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string { return "rect" }
func report(shapes []Shape) {
for _, s := range shapes {
fmt.Printf("%s: %.2f\n", s.Name(), s.Area())
}
}
How it works
- An interface lists required method signatures.
RectsatisfiesShapejust by having them.- Code depends on the interface, not the type.
Keywords and builtins used here
float64forfuncinterfacerangereturnstringstructtype
The run, in numbers
- Lines
- 15
- Characters to type
- 292
- Tokens
- 91
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.
Step 1 of 4 in Interfaces, step 4 of 19 in Interfaces & generics.