Pointer Receivers
Part of the Logic & Flow section of Coddy's GO journey — lesson 8 of 68.
While value receivers work with copies of structs, pointer receivers work directly with the original struct instance. When you define a method with a pointer receiver, the method can modify the original data because it receives a pointer to the struct rather than a copy.
To create a pointer receiver, you add an asterisk * before the type name in the receiver declaration:
type Person struct {
Name string
Age int
}
func (p *Person) haveBirthday() {
p.Age++ // This modifies the original struct
}In this example, (p *Person) is a pointer receiver. When you call the haveBirthday method on a Person instance, the method receives a pointer to the original struct. Any changes made to the struct fields through this pointer will permanently modify the original data.
Pointer receivers are essential when your methods need to update the struct's fields, making them perfect for operations that change the state of 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.
Challenge
EasyIn this challenge, you'll practice creating methods with pointer receivers by building a simple bank account system. You'll create an Account struct and define methods that can modify the account balance using pointer receivers.
You will receive three inputs:
- A string representing the account holder's name (e.g.,
"John Smith") - A string representing the initial account balance (e.g.,
"1000.50") - A string representing a transaction amount (e.g.,
"250.75")
Your task is to:
- Define an
Accountstruct with two fields:Name(string) andBalance(float64) - Create a method called
depositwith a pointer receiver that adds the given amount to the account balance - Create a method called
withdrawwith a pointer receiver that subtracts the given amount from the account balance - Create a method called
displayBalancewith a value receiver that prints the account information in the format:"Account: [name], Balance: $[balance]" - Parse the inputs to create an
Accountinstance - Call
displayBalanceto show the initial balance - Call
depositwith the transaction amount - Call
displayBalanceto show the balance after deposit - Call
withdrawwith the transaction amount - Call
displayBalanceto show the final balance
The balance should be displayed with two decimal places precision. This challenge demonstrates how pointer receivers allow methods to modify the original struct data, unlike value receivers which work with copies.
Cheat sheet
Pointer receivers work directly with the original struct instance by receiving a pointer to the struct rather than a copy. This allows methods to modify the original data.
To create a pointer receiver, add an asterisk * before the type name in the receiver declaration:
type Person struct {
Name string
Age int
}
func (p *Person) haveBirthday() {
p.Age++ // This modifies the original struct
}Use pointer receivers when your methods need to update the struct's fields, making them perfect for operations that change the state of your data.
Try it yourself
package main
import (
"fmt"
"strconv"
)
// TODO: Define the Account struct here
// TODO: Define the deposit method with pointer receiver here
// TODO: Define the withdraw method with pointer receiver here
// TODO: Define the displayBalance method with value receiver here
func main() {
// Read input
var name string
var initialBalanceStr string
var transactionAmountStr string
fmt.Scanln(&name)
fmt.Scanln(&initialBalanceStr)
fmt.Scanln(&transactionAmountStr)
// Convert string inputs to appropriate types
initialBalance, _ := strconv.ParseFloat(initialBalanceStr, 64)
transactionAmount, _ := strconv.ParseFloat(transactionAmountStr, 64)
// TODO: Create an Account instance
// TODO: Display initial balance, perform deposit, display balance, perform withdrawal, display final balance
}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