Menu
Coddy logo textTech

Pointer vs Value Receivers

Part of the Object Oriented Programming section of Coddy's GO journey. Lesson 8 of 107.

Methods can have either a value receiver or a pointer receiver. A value receiver works on a copy of the struct. A pointer receiver works on the original struct and can modify its fields.

Value receiver: works on a copy

type Counter struct {
    Count int
}

func (c Counter) GetCount() int {
    return c.Count
}

// This does NOT modify the original
func (c Counter) IncrementWrong() {
    c.Count++ // Only changes the copy!
}

Pointer receiver: modifies the original

// This DOES modify the original
func (c *Counter) Increment() {
    c.Count++
}

func (c *Counter) Reset() {
    c.Count = 0
}

Using both together

func main() {
    counter := Counter{Count: 0}

    counter.Increment()
    counter.Increment()
    fmt.Println(counter.GetCount()) // Output: 2

    counter.Reset()
    fmt.Println(counter.GetCount()) // Output: 0
}

Use a value receiver when the method only reads data. Use a pointer receiver (*StructName) when the method needs to modify the struct's fields. Go automatically handles the referencing. You call both the same way.

challenge icon

Challenge

Medium

Add methods to the Wallet struct using the correct receiver types:

  • GetBalance: value receiver, returns the current balance
  • Deposit: pointer receiver, adds amount to balance
  • Withdraw: pointer receiver, subtracts amount only if sufficient funds

Try it yourself

package main

import "fmt"

func main() {
    var balance, deposit, withdraw float64
    fmt.Scan(&balance, &deposit, &withdraw)

    w := Wallet{Balance: balance}

    fmt.Printf("Balance: %.2f\n", w.GetBalance())

    w.Deposit(deposit)
    fmt.Printf("After deposit: %.2f\n", w.GetBalance())

    w.Withdraw(withdraw)
    fmt.Printf("After withdrawal: %.2f\n", w.GetBalance())

    fmt.Printf("Final balance: %.2f\n", w.GetBalance())
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Go compiler