Go course

StructsEmbedded Structs

Go

Display

Theme

Structs · Test exercise

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:

  1. buatPenyihir(nama string) Penyihir — a new wizard always starts with Level 1, HP 80, and Mana 120.

  2. 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

main.go
package main

import "fmt"

type Karakter struct {
	Nama  string
	HP    int
	Level int
}

type Penyihir struct {
	Karakter
	Mana int
}

func buatPenyihir(nama string) Penyihir {
	// TODO: isi Karakter (Nama, Level 1, HP 80) dan Mana 120
	return Penyihir{}
}

func infoPenyihir(p Penyihir) string {
	// TODO: gunakan p.Nama, p.Level, p.HP, p.Mana
	return ""
}

func main() {
	m := buatPenyihir("Merlina")
	fmt.Println(infoPenyihir(m))

	m.Level = 5
	m.HP = 140
	fmt.Println(infoPenyihir(m))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)