Skip to Content
Course content

21: Pointer vs Value Receivers

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've already seen how to attach methods to structs in Go, but if you've been writing code for a few days, you've probably noticed there are two ways to define the receiver: (u User) and (u *User). On the surface, they look almost identical. In practice, choosing the wrong one is a classic way to spend an hour wondering why your data isn't actually changing.

Setting up a simple Player profile

Let's build something concrete. Imagine we're making a simple RPG. We need a Player struct to track a character's name and their experience points (XP). I'll start by defining the struct and a method to display their current status.

type Player struct {
    Name string
    XP   int
}

// GetStatus uses a value receiver
func (p Player) GetStatus() string {
    return fmt.Sprintf("%s has %d XP", p.Name, p.XP)
}

In GetStatus, I used a value receiver (p Player). This means every time I call this method, Go makes a complete copy of the Player struct and passes that copy into the function. Since I'm only reading the data to return a string, a copy is perfectly fine. It's safe, and it tells anyone reading my code: "This method will not modify the player."

The "Why isn't this updating?" moment

Now, we need a way to reward the player for completing quests. I want a method that adds XP to the player's total. I'll write it quickly, just like I did for the status method.

func (p Player) AddXP(amount int) {
    p.XP += amount
    fmt.Printf("Added %d XP to %s!\n", amount, p.Name)
}

func main() {
    hero := Player{Name: "Valerius", XP: 0}
    fmt.Println(hero.GetStatus()) // Valerius has 0 XP
    
    hero.AddXP(100)
    
    fmt.Println(hero.GetStatus()) // Still says 0 XP?!
}

Wait. I can see the "Added 100 XP" message in the console, but when I check the status again, Valerius is still at 0 XP. This is the most common "gotcha" for developers new to Go. Because I used a value receiver (p Player), the AddXP method received a copy of the hero. I updated the XP on that copy, the function ended, and the copy was thrown away. The original hero in main remained untouched.

Fixing the state with pointer receivers

To fix this, I need the method to operate on the actual instance of the player, not a copy. I do this by changing the receiver to a pointer: *Player.

// Now using a pointer receiver
func (p *Player) AddXP(amount int) {
    p.XP += amount
}

By using *Player, Go passes the memory address of the struct. Now, when I modify p.XP, I'm modifying the original object. One thing I love about Go is that you don't have to manually dereference the pointer (you don't have to write (*p).XP). Go handles that syntactic sugar for you, so it still looks like p.XP.

Deciding which one to use

You might be tempted to just use pointer receivers for everything to "be safe." Don't do that. It adds unnecessary pressure to the garbage collector because pointer types often escape to the heap. I usually follow these rules of thumb:

  • Use a pointer receiver if the method needs to modify the receiver's state.
  • Use a pointer receiver if the struct is very large. Copying a struct with 50 fields every time you call a method is a waste of CPU and memory.
  • Use a value receiver for small, immutable-like structs or when you want to ensure the method cannot accidentally change the data.

Consistency is also key. If some of your methods must be pointer receivers, it's generally better to make all methods on that struct pointer receivers to keep the API predictable.




📋 Practical Task

Implementing a Character Health System

Create a program that manages a game character's health. You will need to implement a Character struct with Name (string) and Health (int) fields.

  • Implement a method called TakeDamage that subtracts a given amount from the character's health. This method must actually update the character's health in the main program.
  • Implement a method called IsAlive that returns a boolean (true if health is greater than 0). This method should not modify the character and should use a value receiver.
  • In your main function, create a character, deal damage to them multiple times, and print whether they are still alive after each hit.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.