Sobes.tech
Middle

How do interfaces in Go enable polymorphism without explicit inheritance?

sobes.tech AI

Answer from AI

In Go, interfaces define a set of methods that a type must implement, but do not require explicit inheritance. Any type that implements the interface's methods is automatically considered its implementation. This allows for polymorphism — you can work with different types through a common interface without tying them to a class hierarchy.

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 saySomething(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    d := Dog{}
    c := Cat{}
    saySomething(d) // Woof!
    saySomething(c) // Meow!
}

Here, Dog and Cat are not related through inheritance, but both implement the Speaker interface, allowing them to be used polymorphically.

How do interfaces in Go enable polymorphism without… - sobes.tech