Pointer Receivers
Start with Pointer Receivers
A pointer receiver lets a method change the existing value or avoid copying a large receiver on each call.
What you’ll learn
- Explain the main purpose of pointer receivers.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Declare func (c *Counter) Increase() and call it on an addressable Counter variable. Go automatically takes the address in many ordinary method calls, so c.Increase() can work when Increase has a pointer receiver.
Method sets matter for interfaces: *Counter has methods declared with value or pointer receivers, while Counter does not have pointer-receiver methods in its method set. A method-call convenience conversion does not erase that interface rule.
Visualize how it works
Read the labels and compare the identities, types and storage relationships shown here.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
type Counter struct{ Value int }
func (c *Counter) Increase() { c.Value++ }
func main() {
c := Counter{Value: 5}
c.Increase()
c.Increase()
fmt.Println("After calls:", c.Value)
}
Output
After calls: 7Trace what the program does
The receiver refers to c itself. Each call increments its Value field, producing 7 after two calls.
Avoid common mistakes
- A pointer receiver may receive nil; accessing target fields then needs appropriate handling.
- Automatic address-taking in method calls does not make value types implement pointer-only interfaces.
Try it yourself
Add a pointer-receiver Reset method that sets Value to zero after the increments.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Pointer Receivers in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.