"Type embedding" allows for something close to inheritance in Go. If you add a type as a nameless parameter on a struct, the field and methods of that type are "promoted" to the new type.
type Person struct {
Name string
}
func (p Person) sayHi() {
fmt.Printf("Hello, my name is %s!\n", p.Name)
}
type Programmer struct {
Person // important: this shouldn't be named
PreferredIndentationStyle string
}
func main() {
test := Programmer{
Person: Person{
Name: "Matt",
},
PreferredIndentationStyle: "tabs",
}
// You can access Person's methods...
test.sayHi()
// ...and also its properties.
fmt.Printf("%s prefers %s.\n", test.Name, test.PreferredIndentationStyle)
}
Name string
}
func (p Person) sayHi() {
fmt.Printf("Hello, my name is %s!\n", p.Name)
}
type Programmer struct {
Person // important: this shouldn't be named
PreferredIndentationStyle string
}
func main() {
test := Programmer{
Person: Person{
Name: "Matt",
},
PreferredIndentationStyle: "tabs",
}
// You can access Person's methods...
test.sayHi()
// ...and also its properties.
fmt.Printf("%s prefers %s.\n", test.Name, test.PreferredIndentationStyle)
}