-1

For a type to satisfy an interface, the type needs to implement the methods defined in the interface.

However, in the code snippet below, myStruct does not have any methods written, but by using someInterface as anonymous field, it satisfies someInterface.

Can someone help explain why is it? Thank you.

package main

import "fmt"

type someInterface interface {
    method1(int) string
    method2(string) string
}

type myStruct struct {
    someInterface
    body int
}

func main() {
    var foo someInterface
    bar := myStruct{}

    foo = bar // why no compile error??

    fmt.Println(foo)
}
Jyhonn
  • 63
  • 1
  • 7
  • 1
    When you embed a type in a struct, the embedded type's methods get *promoted* to the struct type. When methods get "promoted" then you can invoke them directly from the struct type instead of through the embedded field, i.e. instead of writing `bar.someInterface.method1()` you can now write `bar.method1()`. So essentially this allows the struct type to satisfy the interface without having to implement it explicitly. – mkopriva Aug 07 '21 at 19:01

1 Answers1

2

myStruct embeds someInterface, so it has all the methods defined in that interface. That also means, myStruct has a field called someInterface, which is not initializes, so calling bar.method1 will panic. You have to initialize it before using it.

bar:=myStruct{}
bar.someInterface=someInterfaceImpl{}
bar.method1(0)
bar.method2("")
colm.anseo
  • 19,337
  • 4
  • 43
  • 52
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59