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)reducesHPbydamage, butHPmust not go below0.Minum(ramuan int)increasesHPbyramuan, but it must not exceedMaxHP. A character whoseHPis already0can't be healed.Hidup() boolonly reads, so leave it as a value receiver. ReturntrueifHP > 0.