0

While trying few things in golang related to interfaces I came across the following behaviour which I could not explain

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)
}

When I run this code I get the error as 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

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
}

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 ?

Can someone please let me know if this is the expected behaviour and if so why it is?

Glen D souza
  • 33
  • 1
  • 4
  • 1
    You used a pointer to an `Animal`, but not `Dog` – JimB Apr 27 '22 at 17:01
  • `Dog` and `*Dog` are different types. In your above code `*Dog` implements `Walker` but `Dog` does not. So `CheckWalker(&dog)` will pass compiler checks but `CheckWalker(dog)` will not. Types and interfaces are covered in detail by the Go tutorial (https://go.dev/doc/tutorial/getting-started), please go through that before asking about this stuff here. – BadZen Apr 27 '22 at 18:24

0 Answers0