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:
-
labelPengiriman(p Pelanggan) string(a shipping label) in this format:<Nama> - <Jalan>, <Kota> <KodePos>Example:
Sari - Jl. Melati 5, Bandung 40115 -
pindahAlamat(p Pelanggan, baru Alamat) Pelanggan— return the same customer with the address replaced bybaru(the new address). The name doesn't change.