CodeBlanks Logo Icon CodeBlanks

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).

Practice 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.

Starter code

main.go
package main

import (
    "errors"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
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)
}

Expected output

yetersiz bakiye 70

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 After calling <code>func (h Hesap) Yatir(t float64) { h.Bakiye += t }</code>, does the balance change?

  • No; a value receiver changes a copy Correct answer
  • Yes
  • It doesn't compile
  • Only on the first call

Explanation: A value receiver gets a copy of the struct on each call; *Hesap is needed for the change to stick.

2 A changing method

Question
func (h ____Hesap) Cek(t float64) {
    h.Bakiye -= t
}
Answer
func (h *Hesap) Cek(t float64) {
    h.Bakiye -= t
}

Explanation: The *Hesap receiver lets the method change the real account.

3 Case and receiver

Term Meaning
Change the balance *Hesap
Read a field, small struct Hesap (value)
Struct containing a mutex *T
h.Yatir(1) Go takes &h

All lessons in Beginner