Struct e interfacce
Go Struct Embedding and Composition
Go has no inheritance. Reuse fields and methods by embedding one struct in another.
Cosa imparerai
- 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.
Punti chiave
- Dog embeds Animal and gets Name and Describe.
- The embedded value is still reachable:
dog.Animal. - Embedding is composition, not inheritance.
Esempio Go eseguibile
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 usersEsercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Decorator del prezzo Avvolgi un prezzo base in decoratori di sconto, tassa, spedizione e coupon applicati in ordine. Facile
- Dimensioni delle cartelle con Composite Calcola la dimensione totale di ogni cartella in un albero in cui le cartelle contengono file e altre cartelle. Media