On Thu, Apr 28, 2022 at 9:49 AM Glen D souza <glenpo...@gmail.com> wrote:
> Consider the following piece of code > > type Dog struct { > } > > type Walker interface { > Walks() > } > > func (d *Dog) Walks() { > > } > > func CheckWalker(w Walker) { > > } > > func main() { > dog := Dog{} > CheckWalker(dog) -> cannot use dog (variable of type Dog) as Walker > value in argument to CheckWalker: Dog does not implement Walker (method > Walks has pointer receiver)compilerInvalidIfaceAssign > <https://pkg.go.dev/golang.org/x/tools/internal/typesinternal?utm_source%3Dgopls#InvalidIfaceAssign> > } > > When I run this code I get the error as show in the red above > > Now consider this piece of code > > type Dog struct { > } > > func (d *Dog) Walks() { > > } > > type Bird struct { > } > > func (b *Bird) Flys() { > > } > > type Flyer interface { > Flys() > } > > type Walker interface { > Walks() > } > > type Combined interface { > Walker > Flyer > } > > type Animal struct { > Dog > Bird > } > Look at the Animal struct. The Walks and Flys methods are defined for *Animal, not for Animal. The type Animal has no methods. Because of that, *Animal implements the combined interface, and not Animal. In your main(), you declare animal=&Animal{}, thus the variable `animal` can be used where Combined is required. > > func CheckCombined(c Combined) { > > } > > func Check(w Walker) { > > } > func main() { > animal := &Animal{} > CheckCombined(animal) > } > > This code runs without any error! > Since Animal struct is compose of Dog and Bird (not pointer to them), why > this code is working where as only pointer to Dog and Bird implement the > necessary methods to satisfy the interface Combined ? > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/80a3498b-b1e9-4a30-a55c-ef93a53e89e4n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/80a3498b-b1e9-4a30-a55c-ef93a53e89e4n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAMV2RqqWFrd-SZAVgh%2BbbTzY63ZEpmWU6%2B%2B0bkO-rWvhiaDpSQ%40mail.gmail.com.