Middle+
How is inheritance implemented in Go?
sobes.tech AI
Answer from AI
In Go, there is no classical inheritance like in object-oriented languages. Instead, composition and embedding of structs are used.
A struct can include another struct as an unnamed field, which allows it to "inherit" its methods and fields. This enables code reuse and the construction of complex types from simple ones.
Example:
package main
import "fmt"
type Animal struct {
Name string
}
func (a Animal) Speak() {
fmt.Println(a.Name, "says")
}
type Dog struct {
Animal // embedding
}
func main() {
d := Dog{Animal{Name: "Bobby"}}
d.Speak() // calls Animal's method
}
Here, Dog "inherits" the Speak method from Animal through embedding. This approach allows flexible hierarchy building without classical inheritance.