For example, below, if we delete the calls to Move(c), the code will compile and the subtle bug (which is the fact that Car doesn't implement the right return value for the Move() function) will be overlooked.
The good news: Whats even more subtle here is that there is operator overloading in golang. So the good news is, the Compiler will flag the Move() function on Car as problematic... So long as you exersize the interface.
In short, Please exercise your interfaces, or don't declare them to begin with.
package main
import (
"fmt"
)
type Transporter interface {
Move() int
}
type Car struct{
}
type Boat struct{
}
func (c *Car) Move(){
fmt.Println("vroom!")
}
func (c *Boat) Move() int{
fmt.Println("vroom!")
return 0
}
// make sure to declare a function that uses your interface.
func Move(t Transporter){
x := t.Move()
fmt.Println(x)
}
func main() {
fmt.Println("Hello, playground")
c := &Car{}
b := &Boat{}
// should not compile, because of the fact that Move is not an interface.
// its a good think we tried Move(c) on car, otherwise this interface bug would go unchecked.
Move(c)
Move(b)
}
No comments:
Post a Comment