Go by Example

Struct Embedding

Go has no class inheritance; struct embedding promotes fields and methods while composing types.

Struct embedding is Go's composition pattern. An unnamed field promotes accessible fields and methods to the outer struct; it does not make the outer type a subtype.

Dog gets access to the embedded Animal fields and method. Its own method takes precedence for d.Speak(), while the embedded method remains available through the field.

package main
 
import "fmt"
 
type Animal struct{ Name string }
 
func (a Animal) Speak() string {
    return a.Name + " makes a sound"
}
 
type Dog struct {
    Animal
    Breed string
}
 
func (d Dog) Speak() string {
    return d.Name + " barks"
}
 
func main() {
    d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
    fmt.Println(d.Name, d.Breed, d.Speak())
    fmt.Println(d.Animal.Speak())
}

In production

Promotion can cause a struct to satisfy an interface unintentionally. Use named fields when you want method sets to remain explicit, and add compile-time interface checks when conformance is part of the type's contract.

Enjoyed this? Get more software craft delivered to your inbox.