In Go, function arguments are passed by value by default.
This means the function gets a copy of the value, not the original.
Pass by Value Pass by Pointer
main: main:
score = 10 score = 10
| |
| copy | address
v v
double: double:
n = 10 (separate copy) n = &score (points to original)
n = 20 (copy changed) *n = 20 (original changed)
| |
main: main:
score = 10 (unchanged) score = 20 (modified!)
func double(n int) {
n = n * 2
}
score := 10
double(score)
fmt.Println(score) // 10score is still 10. The function modified a copy, not the original.
To modify the original variable, pass a pointer:
func double(n *int) {
*n = *n * 2
}
score := 10
double(&score)
fmt.Println(score) // 20score is now 20. The function received the address and modified the value at that address.
Notice two things:
- The parameter type is
*int(pointer to int) - The caller passes
&score(address of score)
↳ 1) When you need a function to modify the original value
↳ 2) When you want to avoid copying large data structures
There are some pointer operations in main.go file.
But they are incomplete.
Open main.go file and complete the code lines.
Then validate your code by running:
go run topic.go 29 validate✅ If everything is ok, you should see:
OK!
Now you know how to pass pointers to functions in Go.
Continue to the next topic 👇
