Pointers and method receivers can be confusing when you are learning Go. A common question is: if Go passes arguments by value, how can a method change a struct?
The short answer is that a pointer is also a value. Passing a pointer copies the pointer, not the data it points to. The original pointer and the copy can both refer to the same value.
Go passes arguments by value
Consider a function that accepts a struct:
package main
import "fmt"
type Counter struct { Value int }
func increment(c Counter) { c.Value++ }
func main() { counter := Counter{Value: 1} increment(counter)
fmt.Println(counter.Value) // 1 }
When increment is called, Go copies counter into the parameter c .…