Structs e interfaces
Go Struct Embedding and Composition
Go has no inheritance. Reuse fields and methods by embedding one struct in another.
Lo que aprenderás
- Embedding a struct
- Promoted fields and methods
- Composition
type Dog struct
DogAnimalName, Describe()Breed
Build types from smaller types
Go has no inheritance. Instead, a struct can embed another struct, and the fields and methods of the embedded type become available on the outer one. This is called composition.
Dog embeds Animal, so dog.Name and dog.Describe() work as if they were declared on Dog. The embedded value can still be reached by its type name, as in dog.Animal.Name. Service gets a Log method by embedding Logger.
Puntos clave
- Dog embeds Animal and gets Name and Describe.
- The embedded value is still reachable:
dog.Animal. - Embedding is composition, not inheritance.
Ejemplo ejecutable de Go
main.go
package main
import "fmt"
type Animal struct {
Name string
}
func (a Animal) Describe() string {
return a.Name + " is an animal"
}
type Dog struct {
Animal // embedded: Dog gets Name and Describe
Breed string
}
func (d Dog) Speak() string {
return d.Name + " says woof"
}
type Logger struct{ Prefix string }
func (l Logger) Log(message string) { fmt.Println(l.Prefix + message) }
type Service struct {
Logger
Name string
}
func main() {
dog := Dog{Animal: Animal{Name: "Rex"}, Breed: "Collie"}
fmt.Println(dog.Describe())
fmt.Println(dog.Speak())
fmt.Println(dog.Animal.Name, dog.Breed)
service := Service{Logger: Logger{Prefix: "[api] "}, Name: "users"}
service.Log("started " + service.Name)
}
Rex is an animal
Rex says woof
Rex Collie
[api] started usersPractica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- Decoradores de precio Envuelve un precio base en decoradores de descuento, impuestos, envío y cupón aplicados en orden. Fácil
- Tamaños de carpetas con Composite Calcula el tamaño total de cada carpeta en un árbol donde las carpetas contienen archivos y otras carpetas. Intermedio