Sobes.tech
Junior — Middle

How is polymorphism implemented in the Go language?

sobes.tech AI

Answer from AI

Polymorphism in Go is implemented through interfaces. An interface describes a set of methods, and any type that implements these methods automatically satisfies the interface.

This allows writing functions and methods that work with different types if they implement the required interface.

Example:

package main
import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct {}
func (d Dog) Speak() string {
    return "Woof"
}

type Cat struct {}
func (c Cat) Speak() string {
    return "Meow"
}

func MakeSpeak(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    dog := Dog{}
    cat := Cat{}
    MakeSpeak(dog) // output: Woof
    MakeSpeak(cat) // output: Meow
}

Thus, polymorphism in Go is achieved through interfaces and dynamic method binding at runtime.

How is polymorphism implemented in the Go language… - sobes.tech