Go
Pointer receiver
Learn to mutate a struct from a method with a pointer receiver.
Pointer receivers
If the method must change the receiver, a pointer receiver is used: func (h *Hesap). With a value receiver the method works on a copy and the change is lost:
type Hesap struct{ Bakiye float64 }
func (h *Hesap) Yatir(t float64) {
h.Bakiye += t
}
h := Hesap{}
h.Yatir(100) // Go uses &h automatically
fmt.Println(h.Bakiye) // 100
Which receiver?
The rule is simple: pointer if the method changes the receiver, the struct is large, or it contains fields that must not be copied such as sync.Mutex; value for small, unchanging data. A type's methods should be consistent: if one uses a pointer receiver, usually all do. In a call like h.Yatir() Go takes the address itself, but only for addressable variables (e.g. Hesap{}.Yatir(1) doesn't compile).
Exercise Bank account
Write the pointer-receiver methods Yatir(t float64) and Cek(t float64) error for Hesap; on insufficient balance return errors.New("yetersiz bakiye"). Deposit 100, withdraw 30, then try to withdraw 200; print the error and the final balance.
Show example solution
package main
import (
"errors"
"fmt"
)
type Hesap struct{ Bakiye float64 }
func (h *Hesap) Yatir(t float64) { h.Bakiye += t }
func (h *Hesap) Cek(t float64) error {
if t > h.Bakiye {
return errors.New("yetersiz bakiye")
}
h.Bakiye -= t
return nil
}
func main() {
var h Hesap
h.Yatir(100)
h.Cek(30)
err := h.Cek(200)
fmt.Println(err, h.Bakiye)
}
Test yourself
-
After calling <code>func (h Hesap) Yatir(t float64) { h.Bakiye += t }</code>, does the balance change?
- No; a value receiver changes a copy
- Yes
- It doesn't compile
- Only on the first call
Show answer
No; a value receiver changes a copy — A value receiver gets a copy of the struct on each call; *Hesap is needed for the change to stick.
-
A changing method
func (h ____Hesap) Cek(t float64) {
h.Bakiye -= t
}
Show answer
func (h *Hesap) Cek(t float64) {
h.Bakiye -= t
}
-
Case and receiver
- Change the balance
- *Hesap
- Read a field, small struct
- Hesap (value)
- Struct containing a mutex
- *T
- h.Yatir(1)
- Go takes &h
Next lesson: Value receiver