3 ms·
I don't speak Go. Is there some magic here that lets Dog and Cat know that they're implementing Animal? Or are you just informing MakeNoises(as ...Animal) that
by noduerme 4y ago
I don't speak Go. Is there some magic here that lets Dog and Cat know that they're implementing Animal? Or are you just informing MakeNoises(as ...Animal) that it will be receiving something that should implement Animal, with no compile-time type checking?
Being able to specify that an argument conforms to an interface is not what's generally meant by "object oriented". Interfaces are really only a formality. What matters is inheritance.
- rakoo 4y 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 4y 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 4y 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 4y 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! }
- deleted 4y ago[deleted]
- cube2222 4y agoGo has duck-typed interfaces. It will make sure that only values implementing Animal will ever be used as an Animal anywhere. It's fully statically type-checked. It's arguably one of the defining features of Go in general, and is what shapes much of the idiomatic code style.
- deleted 4y ago[deleted]
- bheadmaster 4y ago> Is there some magic here that lets Dog and Cat know that they're implementing Animal? In this case, Animal is an interface - which means, a set of methods. The Animal interface in the example contains only a method "MakeNoise()". Any type (struct) that implements the method "MakeNoise()" implements the interface, and can be used whenever Animal is required.
- deleted 4y ago[deleted]