Sobes.tech
Junior — Middle

How does the compiler determine which specific method to call in case of overloading or overriding?

sobes.tech AI

Answer from AI

Go does not have method overloading in the traditional sense like C++ or Java. Each method or function has a unique name within a package. If there are multiple functions with the same name but different parameters, it will cause a compile-time error.

Regarding overriding, Go uses interfaces: if a type implements the methods of an interface, then calling through the interface will invoke the method of the specific type.

Thus, method selection occurs at compile time based on the function's name and signature, while dynamic dispatch through an interface is determined by the object's type at runtime.

Example:

package main
import "fmt"

type Speaker interface {
    Speak()
}

type Dog struct{}
func (d Dog) Speak() { fmt.Println("Woof") }

type Cat struct{}
func (c Cat) Speak() { fmt.Println("Meow") }

func main() {
    var s Speaker
    s = Dog{}
    s.Speak() // Outputs Woof
    s = Cat{}
    s.Speak() // Outputs Meow
}