Pass by Value vs Pass by Pointer
In Go, every function argument is passed as a copy (pass by value). For a struct, that means every field is copied. A function that changes the copy doesn't affect the original:
type Dompet struct {
Pemilik string
Saldo int
}
func isiSaldo(d Dompet, n int) {
d.Saldo += n // hanya mengubah salinan
}
dw := Dompet{Pemilik: "Rani", Saldo: 10000}
isiSaldo(dw, 5000)
fmt.Println(dw.Saldo) // 10000 — tidak berubah!
The balance hasn't changed! To make the change visible, pass a pointer to the struct. Now only the address is copied, so the function works on the same data:
func isiSaldo(d *Dompet, n int) {
d.Saldo += n
}
isiSaldo(&dw, 5000)
fmt.Println(dw.Saldo) // 15000
Notice d.Saldo, not (*d).Saldo. Go dereferences automatically when you access a field through a pointer to a struct. Both are valid, but the short form is more common.
Creating a pointer to a struct directly
dp := &Dompet{Pemilik: "Bayu", Saldo: 0} // dp bertipe *Dompet
What about slices and maps?
Slices and maps are copied too, but the copy still refers to the same underlying data. That's why changing a slice element or a map's contents inside a function is visible to the caller, while an append that creates a new array isn't (remember Chapter 9).
Task
The digital wallet program in the editor has a bug: the balance never changes. Fix the isiSaldo and bayar functions so they take a *Dompet, then adjust how they're called in main.
bayaronly reduces the balance if there's enough, and returnstrueif it succeeds.
Expected output:
Saldo awal: 20000
Setelah isi saldo: 70000
Bayar 45000: true
Bayar 30000: false
Saldo akhir: 25000