Struct embedding

Struct embedding in Go promotes fields and methods from an anonymous inner struct to the outer struct for code reuse and composition.

Struct embedding in Go allows a struct to include another struct as an anonymous field, automatically promoting its methods and fields to the outer struct's scope. This mechanism enables code reuse and composition without explicit inheritance.

type Animal struct {
    Name string
}

func (a *Animal) Speak() { fmt.Println(a.Name + " speaks") }

type Dog struct {
    Animal // Embedded struct
    Breed  string
}

func main() {
    d := Dog{Animal: Animal{Name: "Buddy"}, Breed: "Poodle"}
    d.Speak() // Output: Buddy speaks
}