3 ms·
> Is there some magic here that lets Dog and Cat know that they're implementing Animal? No there isn't and that's the point. Say you're building a lib and some
by rakoo 3y ago
> Is there some magic here that lets Dog and Cat know that they're implementing Animal?
No there isn't and that's the point. Say you're building a lib and someone else wants to reuse it and its methods and extract functionality into a more generic interface; as the original author you don't need to go and modify your lib to accommodate for every single third party dev out there.
Basically, the interface might be in another package, and that's fine.
> with no compile-time type checking?
The compiler will still check if Dog and Cat implement the interface, because at compile time everything is known.
- noduerme 3y agoBut then Dog and Cat need to both contain [edit] explicitly reproduce, verbatim [/edit] all the common functions of "Animal" - even if they're exactly the same? Just so someone later can take Dog and reuse it without implementing Animal?
- cube2222 3y agoYou can use struct embedding to accomplish that if you need it (Embed Dog / Animal in a new struct which adds/modifies functionality). Though this is used fairly rarely in Go.
- rakoo 3y agoAnimal is an interface: it has no "common functions", they're just definitions. If you need a common function, what you want is another structure, say Pet, and use structure embedding type Pet struct { func IsCute() bool {return yes} } type Dog struct { Pet # note how it is not named } func (Dog) MakeNoise() { fmt.Println("Woof!") } func main() { d := Dog{} d.IsCute() # yes # A third party lib type Chihuaha struct { Dog } c := Chihuaha {} c.IsCute() # yes c.MakeNoise() # Woof! }