Struct Embedding
Embed a struct to reuse its fields and methods. It is composition, not inheritance.
Example
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 main() {
d := Dog{Animal{"Rex"}, "labrador"}
fmt.Println(d.Name, d.Speak(), d.Breed)
}Result
Rex Rex makes a sound labrador
Exercise
Reuse fields.
type Dog struct { }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.