Go by Example

Struct Embedding

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

Struct embedding puts one struct inside another without writing a separate field name. Go lets the outer struct use the inner struct's fields and methods directly. The outer struct remains its own type.

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

An interface defines the methods a value must provide to be used in a particular way. Embedding can add methods that make a struct satisfy an interface when you did not intend it. Use a named field when you want access to stay explicit, such as d.Animal.Speak(). Add a compiler check when the struct must provide an interface's methods.

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