4 ms·
While Go interfaces are usually checked at compile time, this doesn't have to be the case - you don't even have to use reflection. Consider the following progra
by GlitchMr 7y ago
While Go interfaces are usually checked at compile time, this doesn't have to be the case - you don't even have to use reflection. Consider the following program.
package main
import "fmt"
type Dog struct{}
func (d Dog) NumberOfLegs() int {
return 4
}
func (d Dog) Genus() string {
return "Canin"
}
func main() {
var dog interface{} = Dog{}
fmt.Println(dog.(interface{ NumberOfLegs() int }).NumberOfLegs())
fmt.Println(dog.(interface{ Genus() string }).Genus())
fmt.Println(dog.(interface{ Happy() bool }).Happy())
}
This fails at runtime, as `Dog` doesn't have `Happy` method.
- loopz 7y agoWhy do good people downvote what they don't understand? https://play.golang.org/p/d0TkGTCZa2S https://play.golang.org/p/d0TkGTCZa2S Runtime results in panic: 4 Canin panic: interface conversion: main.Dog is not interface { Happy() bool }: missing method Happy goroutine 1 [running]: main.main() /tmp/sandbox251002434/prog.go:18 +0x200 Using interface casting, Golang do support "duck typing" in similar fashion as ruby's Object class. Here, by convention, the instance of Dog doesn't support "type" Happy(), therefore fails at runtime. So golang is somewhat dynamic as well, although using interface{} is kludgy and one would want to avoid that and reflection whenever possible.