Mutate through pointer parameters
Mutate through pointer parameters
Go passes arguments by value, including pointers. A function receiving an int gets a copy of the integer. A function receiving *int gets a copy of the pointer, which can still refer to the caller’s variable. This makes deliberate in-place mutation possible.
package main
import ( "fmt")
func incrementValue(n int) { n++ }func increment(p *int) { *p += 1 }func main() { n := 5 incrementValue(n) fmt.Println(n) increment(&n) fmt.Println(n)}incrementValue changes only its local parameter. increment changes the variable referenced by the copied pointer. Its contract requires a non-nil pointer. For simple calculations, returning a new value can be clearer than mutating an argument.
Expected output:
56Reassigning the parameter is different
package main
import ( "fmt")
func redirect(p *int, q *int) { p = q; *p = 30 }func main() { a, b := 10, 20 p := &a redirect(p, &b) fmt.Println(*p, a, b)}Reassigning the local p changes only that copy of the pointer. The caller’s p still refers to a. The write through the new local p updates b. Return a new pointer if the caller needs to replace its own pointer variable.
Expected output:
10 10 30Try it locally
Write swap(a,b *int) that swaps the pointed-to integers. Call it with addresses of variables containing 3 and 9; print both. Assume non-nil arguments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pointers and ownership 03: Mutate through pointer parameters
Check the lesson objective before moving on.
How is a pointer argument passed in Go?
Which statement updates the caller’s int through p?