Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
21: Pointer vs Value Receivers
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
TakeDamagethat 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
IsAlivethat 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
mainfunction, create a character, deal damage to them multiple times, and print whether they are still alive after each hit.
There are no comments for now.