Embedded Structs
Go doesn't have inheritance like classic object-oriented languages. Instead, Go uses composition: a struct can embed another struct by writing just its type name, with no field name.
type Karakter struct {
Nama string
HP int
Level int
}
type Pemanah struct {
Karakter // embedded: tanpa nama field
JumlahPanah int
}
Here a Pemanah (archer) embeds Karakter (character) and adds its own arrow count.
"Promoted" fields
The fields of an embedded struct can be accessed directly, as if they belonged to the outer struct:
p := Pemanah{
Karakter: Karakter{Nama: "Laras", HP: 90, Level: 3},
JumlahPanah: 40,
}
fmt.Println(p.Nama) // Laras (dipromosikan)
fmt.Println(p.Karakter.Nama) // Laras (cara lengkap, juga valid)
p.Nama is the promoted field; p.Karakter.Nama is the full path, and it's valid too.
Note: when creating the value, you still write the embedded struct as a field named after its type (Karakter: Karakter{...}).
How it differs from a nested struct
type A struct {
Karakter Karakter // bersarang: harus a.Karakter.Nama
}
type B struct {
Karakter // embedded: cukup b.Nama
}
With a nested struct you have to write a.Karakter.Nama; with an embedded one, b.Nama is enough.
Task
An RPG has several character classes that share the basic Karakter data. The Penyihir (wizard) type already embeds Karakter. Complete:
-
buatPenyihir(nama string) Penyihir— a new wizard always starts withLevel1,HP80, andMana120. -
infoPenyihir(p Penyihir) string— use the promoted fields, in this format:<Nama> [Lv <Level>] HP:<HP> Mana:<Mana>Example:
Merlina [Lv 1] HP:80 Mana:120