Value Receivers
Start with Value Receivers
A value receiver receives a copy of its receiver when a method runs. This works well for small read-only values.
What you’ll learn
- Explain the main purpose of value receivers.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
In func (c Counter) Next() int, the method receives a Counter value. Reassigning fields of that local receiver does not modify the original Counter value held by the caller.
Value receivers can still observe shared data inside fields such as slices or maps: copying the struct copies those field values, not necessarily their underlying storage. Prefer a consistent receiver style for a type where possible.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
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() int {
c.Value++
return c.Value
}
func main() {
c := Counter{Value: 5}
fmt.Println("Returned:", c.Increase())
fmt.Println("Original:", c.Value)
}
Output
Returned: 6
Original: 5Trace what the program does
The method increments only its local copy of c to 6 and returns it. The caller’s c.Value remains 5.
Avoid common mistakes
- Do not expect a value-receiver field assignment to update the original struct.
- A struct copy may still share map or slice storage inside its fields.
Try it yourself
Make a value-receiver method that doubles an integer field, returns the doubled value and leaves the original unchanged.
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 Value 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.