Interfaces are satisfied implicitly in Go
No implements keyword: a type has the methods, so it fits.
type Scorer interface {
Score() int
}
type Snippet struct{ Lines int }
type Script struct{ Lines int }
func (s Snippet) Score() int { return s.Lines }
func (s Script) Score() int { return s.Lines * 2 }
var _ Scorer = Snippet{} // fails to compile if the method is missing
func total(items []Scorer) int {
sum := 0
for _, item := range items {
sum += item.Score()
}
return sum
}
How it works
- The interface can be declared after the types that satisfy it.
- Small interfaces are the Go habit — often one method.
- A compile-time assertion documents the intent.
Keywords and builtins used here
forfuncintinterfacerangereturnstructtypevar
The run, in numbers
- Lines
- 19
- Characters to type
- 382
- Tokens
- 95
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 57 seconds.
Step 2 of 4 in Interfaces, step 5 of 19 in Interfaces & generics.