Junior — Middle
Kas saaksite selgitada päriluse printsiipi ja kuidas see on rakendatud Go keeles?
sobes.tech AI
Vastus AI-lt
In the Go language, there is no classic inheritance as in other object-oriented languages. Instead, Go uses composition and embedding for code reuse and extending functionality.
Embedding allows including one type (structure) into another, and the methods of the embedded type become accessible to the outer type, similar to inheritance.
Example:
type Animal struct {
Name string
}
func (a Animal) Speak() string {
return "..."
}
// Embedding Animal into Dog
type Dog struct {
Animal
}
func (d Dog) Speak() string {
return "Woof!"
}
func main() {
dog := Dog{Animal{Name: "Buddy"}}
fmt.Println(dog.Name) // Access to Animal field
fmt.Println(dog.Speak()) // Overridden method
}
Thus, Go achieves a similar effect to inheritance through composition and embedding, avoiding the complexities of a classical hierarchy.