Go course

PointersPointer Receivers vs Value Receivers

Go

Display

Theme

Pointers · Test exercise

Pointer Receivers vs Value Receivers

In Chapter 5 you created methods with a receiver like func (k Karakter) .... That's a value receiver: the method gets a copy of the struct. The rules are the same as for ordinary function parameters, so changes to its fields don't stick.

type Lampu struct{ Nyala bool }

func (l Lampu) Saklar() { l.Nyala = !l.Nyala } // mengubah salinan, sia-sia

func (l *Lampu) SaklarBenar() { l.Nyala = !l.Nyala } // pointer receiver

Saklar changes a copy, so it's pointless. With a pointer receiver (*Lampu), the method works on the original struct.

Go helps you call it

You don't need to write (&lampu).SaklarBenar(). If the variable is addressable (a local variable, for example), Go takes its address automatically:

lampu := Lampu{}
lampu.SaklarBenar()      // otomatis menjadi (&lampu).SaklarBenar()
fmt.Println(lampu.Nyala) // true

It works the other way too: a method with a value receiver can be called on a pointer, and Go dereferences it automatically.

When to use which?

  • Use a pointer receiver if the method needs to change state, or the struct is large and expensive to copy.
  • Use a value receiver for methods that only read and when the struct is small.
  • Consistency: if some of a type's methods already use a pointer receiver, usually all of that type's methods use a pointer receiver as well.

How this relates to interfaces

A method with a pointer receiver only belongs to the pointer type's method set. So if Serang() is defined on *Ksatria, it's *Ksatria that satisfies the Penyerang interface, not Ksatria:

var p Penyerang = &Ksatria{} // OK
var q Penyerang = Ksatria{}  // error kompilasi

The second line is a compile error.

Task

The RPG character in the editor never gets hurt or heals, because all of its methods use value receivers. Fix the methods that change state so they use a pointer receiver, and complete their logic:

  • KenaSerang(damage int) reduces HP by damage, but HP must not go below 0.
  • Minum(ramuan int) increases HP by ramuan, but it must not exceed MaxHP. A character whose HP is already 0 can't be healed.
  • Hidup() bool only reads, so leave it as a value receiver. Return true if HP > 0.
main.go
package main

import "fmt"

type Karakter struct {
	Nama  string
	HP    int
	MaxHP int
}

// TODO: method ini harus mengubah karakter aslinya
func (k Karakter) KenaSerang(damage int) {
	k.HP -= damage
}

// TODO: method ini harus mengubah karakter aslinya, dan batasi HP <= MaxHP
func (k Karakter) Minum(ramuan int) {
	k.HP += ramuan
}

func (k Karakter) Hidup() bool {
	return k.HP > 0
}

func main() {
	hero := Karakter{Nama: "Arya", HP: 100, MaxHP: 100}
	hero.KenaSerang(30)
	fmt.Println(hero.Nama, "HP:", hero.HP)
	hero.Minum(50)
	fmt.Println(hero.Nama, "HP:", hero.HP)
	hero.KenaSerang(150)
	fmt.Println(hero.Nama, "HP:", hero.HP, "hidup:", hero.Hidup())
}

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)