

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Introduction to Pointers
incomplete
2: References
incomplete
3: Pass by Reference
incomplete
4: Pointers Quiz
incomplete
5: Nil Pointers
incomplete
6: Pointer Receivers
incomplete
7: Pointer Receiver Code
incomplete
8: Pointer Performance
incomplete
9: Update Balance
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Functions in Go generally pass variables by value, meaning that functions receive a copy of most non-composite types:
func increment(x int) {
x++
fmt.Println(x)
// 6
}
func main() {
x := 5
increment(x)
fmt.Println(x)
// 5
}
The main function still prints 5 because the increment function received a copy of x.
One of the most common use cases for pointers in Go is to pass variables by reference, meaning that the function receives the address of the original variable, not a copy of the value. This allows the function to update the original variable's value.
func increment(x *int) {
*x++
fmt.Println(*x)
// 6
}
func main() {
x := 5
increment(&x)
fmt.Println(x)
// 6
}
When your function receives a pointer to a struct, you might try to access a field like this and encounter an error:
msgTotal := *analytics.MessagesTotal
Instead, access it – like you'd normally do – using a selector expression.
msgTotal := analytics.MessagesTotal
This approach is the recommended, simplest way to access struct fields in Go, and is shorthand for:
(*analytics).MessagesTotal
Write an analyzeMessage function. It should accept a pointer to an Analytics struct and a Message struct (not a pointer).
It should look at the Success field of the Message struct and, based on that, increment the MessagesTotal, MessagesSucceeded, or MessagesFailed fields of the Analytics struct as appropriate.