Value Receivers
Part of the Logic & Flow section of Coddy's GO journey — lesson 7 of 68.
When you define a method with a value receiver, the method operates on a copy of the struct instance rather than the original. This means any changes made to the receiver inside the method will not affect the original struct variable.
type Counter struct {
Value int
}
func (c Counter) increment() {
c.Value++ // This modifies the copy, not the original
}In this example, the increment method has a value receiver (c Counter). When you call this method on a Counter instance, Go creates a copy of the struct and passes it to the method. Any modifications to c.Value inside the method only affect this copy.
Value receivers are useful when your method only needs to read data from the struct without modifying it. They're safe to use because they guarantee the original data remains unchanged, making your code more predictable and preventing unintended side effects.
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 working with value receivers by creating a simple temperature monitoring system. You'll create a Sensor struct and define methods that demonstrate how value receivers work with copies of the struct.
You will receive three inputs:
- A string representing the sensor ID (e.g.,
"TEMP001") - A string representing the current temperature reading (e.g.,
"23.5") - A string representing a temperature adjustment value (e.g.,
"2.0")
Your task is to:
- Define a
Sensorstruct with two fields:ID(string) andTemperature(float64) - Create a method called
displayReadingwith a value receiver that prints the sensor information in the format:"Sensor [ID]: [temperature]°C" - Create a method called
adjustTemperaturewith a value receiver that adds the adjustment value to the temperature and prints:"Adjusted reading: [new_temperature]°C" - Parse the inputs to create a
Sensorinstance - Call the
displayReadingmethod to show the original temperature - Call the
adjustTemperaturemethod with the adjustment value - Call the
displayReadingmethod again to demonstrate that the original struct remains unchanged
This challenge will demonstrate that methods with value receivers work on copies of the struct, so the original struct's temperature value will remain unchanged even after calling the adjustTemperature method. The temperature values should be displayed with one decimal place precision.
Cheat sheet
Value receivers operate on a copy of the struct instance, not the original. Changes made inside the method don't affect the original struct.
type Counter struct {
Value int
}
func (c Counter) increment() {
c.Value++ // This modifies the copy, not the original
}Value receivers are useful when methods only need to read data without modifying the original struct, making code more predictable and preventing unintended side effects.
Try it yourself
package main
import (
"fmt"
"strconv"
)
// TODO: Define your Sensor struct here
// TODO: Define your displayReading method with value receiver here
// TODO: Define your adjustTemperature method with value receiver here
func main() {
// Read inputs
var sensorID string
var tempStr string
var adjustStr string
fmt.Scanln(&sensorID)
fmt.Scanln(&tempStr)
fmt.Scanln(&adjustStr)
// Parse temperature and adjustment values
temperature, _ := strconv.ParseFloat(tempStr, 64)
adjustment, _ := strconv.ParseFloat(adjustStr, 64)
// TODO: Create a Sensor instance and call the required methods
}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