

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
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
A receiver type on a method can be a pointer.
Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are more common than value receivers. However, methods with pointer receivers don't require that a pointer is used to call the method. The pointer will automatically be derived from the value.
type car struct {
color string
}
func (c *car) setColor(color string) {
c.color = color
}
func main() {
c := car{
color: "white",
}
c.setColor("blue")
fmt.Println(c.color)
// prints "blue"
}
type car struct {
color string
}
func (c car) setColor(color string) {
c.color = color
}
func main() {
c := car{
color: "white",
}
c.setColor("blue")
fmt.Println(c.color)
// prints "white"
}
The non-pointer receiver example prints "white" instead of "blue" because the method receives a copy of the struct. Without using a pointer receiver, any changes made inside the method only affect that copy, not the original.