Go course

StructsNested Structs

Go

Display

Theme

Structs · Test exercise

Nested Structs

A struct's field can have another struct as its type. This is called a nested struct:

type Alamat struct {
	Jalan   string
	Kota    string
	KodePos string
}

type Pelanggan struct {
	Nama   string
	Alamat Alamat
}

Here a Pelanggan (customer) has a name and an Alamat (address) with a street, city, and postal code.

Creating and accessing it:

p := Pelanggan{
	Nama: "Sari",
	Alamat: Alamat{
		Jalan:   "Jl. Melati 5",
		Kota:    "Bandung",
		KodePos: "40115",
	},
}

fmt.Println(p.Alamat.Kota) // Bandung

Structs are copied on assignment

A struct is a value. Copying it into another variable or passing it to a function makes a complete copy — including any structs inside it:

salinan := p
salinan.Alamat.Kota = "Bogor"

fmt.Println(p.Alamat.Kota)       // Bandung (asli tidak berubah)
fmt.Println(salinan.Alamat.Kota) // Bogor

The original p still says Bandung; only the copy changed.

That's why a function that wants to "change" a struct usually returns the modified struct. (The other way, with pointers, is covered in the Pointers chapter.)

Comparing structs

You can compare two structs with == as long as all their fields are comparable. The result is true when every field is equal.

Task

A shipping service uses the Alamat and Pelanggan types shown above. Complete:

  1. labelPengiriman(p Pelanggan) string (a shipping label) in this format:

    <Nama> - <Jalan>, <Kota> <KodePos>

    Example: Sari - Jl. Melati 5, Bandung 40115

  2. pindahAlamat(p Pelanggan, baru Alamat) Pelanggan — return the same customer with the address replaced by baru (the new address). The name doesn't change.

main.go
package main

import "fmt"

type Alamat struct {
	Jalan   string
	Kota    string
	KodePos string
}

type Pelanggan struct {
	Nama   string
	Alamat Alamat
}

func labelPengiriman(p Pelanggan) string {
	// TODO: akses field bersarang lewat p.Alamat
	return p.Nama
}

func pindahAlamat(p Pelanggan, baru Alamat) Pelanggan {
	// TODO: ganti alamat lalu kembalikan p
	return p
}

func main() {
	sari := Pelanggan{
		Nama:   "Sari",
		Alamat: Alamat{Jalan: "Jl. Melati 5", Kota: "Bandung", KodePos: "40115"},
	}
	fmt.Println(labelPengiriman(sari))

	pindah := pindahAlamat(sari, Alamat{Jalan: "Jl. Kenari 12", Kota: "Bogor", KodePos: "16128"})
	fmt.Println(labelPengiriman(pindah))
	fmt.Println(labelPengiriman(sari))
}

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)