Struct Embedding
Go no tiene herencia de clases. En su lugar, incrustas un struct dentro de otro listando su tipo sin nombre de campo — el tipo exterior obtiene automáticamente acceso directo a los campos y methods del tipo incrustado, un patrón llamado promoción.
package main
import "fmt"
type Animal struct {
Name string
}
func (a Animal) Describe() string {
return a.Name + " is an animal"
}
type Dog struct {
Animal
Breed string
}
func main() {
d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
fmt.Println(d.Name)
fmt.Println(d.Describe())
}Rex Rex is an animal
Sobrescribir un method promovido
d.Name y d.Describe() de arriba se promueven directamente desde el Animal incrustado, sin necesitar código extra. Un tipo también puede definir su propio method con el mismo nombre para tener precedencia sobre el incrustado, aún llamando explícitamente a través de él, como hace Derived.Label abajo.
package main
import "fmt"
type Base struct {
ID int
}
func (b Base) Label() string {
return fmt.Sprintf("Base#%d", b.ID)
}
type Derived struct {
Base
Name string
}
func (d Derived) Label() string {
return fmt.Sprintf("%s (%s)", d.Base.Label(), d.Name)
}
func main() {
d := Derived{Base: Base{ID: 7}, Name: "widget"}
fmt.Println(d.Label())
}Base#7 (widget)
Siguiente: la librería estándar — un par de paquetes de uso común, y un vistazo final a qué más ofrece la librería estándar de Go.
Practice exercise
Define un struct Vehicle con el campo Wheels int. Define un struct Car que incrusta Vehicle y agrega un campo Brand string. Crea un Car con Wheels 4 y Brand "Toyota", luego imprime car.Wheels y car.Brand.