Why does reassigning a pointer parameter not change the caller's pointer?
Predict what this program prints and explain why. Then change changeName so the second line prints Alice instead.
type Person struct{ Name string }
func changeName(person *Person) {
person = &Person{Name: "Alice"}
}
func main() {
person := &Person{Name: "Bob"}
fmt.Println(person.Name)
changeName(person)
fmt.Println(person.Name)
}
Diagnose the cause, then fix it.
It prints Bob twice. changeName receives a copy of the pointer; reassigning person = &Person{...} only repoints that local copy, leaving the caller untouched. Go has no pass-by-reference. Fix: mutate through it — person.Name = "Alice".
- ✗Believing a pointer parameter means the caller's pointer itself can be repointed inside the function
- ✗Thinking Go passes arguments by reference rather than always by value (including the pointer value)
- ✗Assuming the reassignment line fails to compile rather than just being a no-op for the caller
- →How would you let a function repoint the caller's variable to a brand-new
Person? - →What does
*person = Person{Name: "Alice"}do differently fromperson = &Person{...}?
What it prints
The program prints Bob twice.
In Go everything is passed by value, including pointers. The parameter person *Person is a copy of the caller's pointer: both copies initially point at the same Person{Name: "Bob"}. The line person = &Person{Name: "Alice"} assigns a new address to the local copy — it now points at a fresh struct, but the pointer back in main still holds the old address. So after the call returns, person.Name in main is still Bob.
This is a common trap: "I passed a pointer, so I'm working on the original." Passing a pointer gives access to the struct it points at, not to the caller's pointer variable itself.
The fix
Mutate the field through the pointer instead of reassigning the pointer:
func changeName(person *Person) {
person.Name = "Alice" // same as (*person).Name = "Alice"
}
Now the function writes into the struct at the shared address, and main prints Bob then Alice. If you genuinely need to repoint the caller's variable at a new struct, pass a pointer-to-pointer (**Person) or return the new value and assign it in main.