-2

How is actually methods in Go get dispatched if we use interface, static(compile time) or dynamic(run time). Let consider this code:

package main

import "fmt"

type ICat interface {
    Meow()
    Walk()
    Run()
}
func NewCat(name string) ICat {
    return &cat{
        name:name,
    }
}
type cat struct {
    name string
}
func (c *cat) Meow() {
    fmt.Print("Meowwwwwwwww")
}
func (c *cat) Walk() {
    fmt.Print("Walk")
}
func (c *cat) Run() {
    fmt.Print("Run")
}


type IAnimal interface{
    DoSound()
}
type animal struct {
    cat ICat
}
func New() IAnimal {
    return &animal{
        cat:NewCat("bobby"),
    }
}
func (a *animal) DoSound() {
    a.cat.Meow()
}


func main() {
    i := New()
    i.DoSound()
}

Go Playground: https://play.golang.org/p/RzipDT6FAC9

How actually those methods defined in those interface got dispatched?, I use this style of development to implement interface segregation and separation of concern between data and behaviour. My other concern is the perf. Some said it's statically dispatched at compile time, while other said it's dynamically dispatched at run time.

Jake Muller
  • 925
  • 4
  • 18
  • 25
  • The language makes no guarantees here. Any compiler might do what it find most appropriate and even do things different on Monday. – Volker Apr 22 '20 at 05:24
  • 1
    "Some said it's statically dispatched at compile time" That's impossible in the general case because [the compiler can't always know the dynamic type](https://play.golang.org/p/w2i7W-rKtfP) (that's why it's called *dynamic*). There may not even exist an implementation of an interface at compile time. – Peter Apr 22 '20 at 07:30

1 Answers1

0

We cannot know at compile time what the dynamic type of an interface value will be, A call through an interface must use dynamic dispatch. Instead of a direct call, the compiler must generate code to obtain the address of the method from the type descriptor, then make an indirect call to that address.

Adriel Artiza
  • 327
  • 4
  • 12