Go course

PointersPass by Value vs Pass by Pointer

Go

Display

Theme

Pointers · Output exercise

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.

  • bayar only reduces the balance if there's enough, and returns true if it succeeds.

Expected output:

Saldo awal: 20000
Setelah isi saldo: 70000
Bayar 45000: true
Bayar 30000: false
Saldo akhir: 25000
main.go
package main

import "fmt"

type Dompet struct {
	Pemilik string
	Saldo   int
}

// TODO: ubah parameter menjadi *Dompet
func isiSaldo(d Dompet, jumlah int) {
	d.Saldo += jumlah
}

// TODO: ubah parameter menjadi *Dompet
func bayar(d Dompet, harga int) bool {
	if d.Saldo < harga {
		return false
	}
	d.Saldo -= harga
	return true
}

func main() {
	dw := Dompet{Pemilik: "Rani", Saldo: 20000}
	fmt.Println("Saldo awal:", dw.Saldo)

	isiSaldo(dw, 50000)
	fmt.Println("Setelah isi saldo:", dw.Saldo)

	fmt.Println("Bayar 45000:", bayar(dw, 45000))
	fmt.Println("Bayar 30000:", bayar(dw, 30000))
	fmt.Println("Saldo akhir:", dw.Saldo)
}

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)