Choosing Receivers
Part of the Logic & Flow section of Coddy's GO journey — lesson 9 of 68.
Now that you understand both value and pointer receivers, the key question is: when should you use each one? The decision comes down to what your method needs to do with the receiver.
Use a pointer receiver when your method needs to modify the original struct. Since pointer receivers work with the actual struct instance, any changes made inside the method will persist after the method returns. This is essential for methods that update fields, change state, or perform operations that should affect the original data.
Use a value receiver when your method only needs to read data from the struct without changing it. Value receivers work with a copy, so they're perfect for methods that calculate values, format output, or perform any operation that doesn't require modifying the original struct. They also provide safety by guaranteeing that the original data remains unchanged.
As a general rule: if your method changes the struct, use a pointer receiver. If your method only reads from the struct, use a value receiver. This approach makes your code's intentions clear and helps prevent unintended modifications to your data.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Cheat sheet
Use a pointer receiver when your method needs to modify the original struct:
- Changes made inside the method will persist after the method returns
- Essential for methods that update fields or change state
Use a value receiver when your method only needs to read data from the struct:
- Works with a copy, so original data remains unchanged
- Perfect for methods that calculate values or format output
- Provides safety by guaranteeing no unintended modifications
General rule: If your method changes the struct, use a pointer receiver. If your method only reads from the struct, use a value receiver.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors