The value of a variable can be passed to a function in several ways:
- Value: A copy of the variable’s value is passed so that the function can work with it in its local scope.
- Reference: The memory address (pointer) where the variable is located is passed, making it a “shared” variable.
If you’re new to the Go world, I recommend the following previous articles:
In Go, to obtain the memory address of a variable, we will refer to it as follows:
&VARIABLE_NAME
If a function is going to receive a variable as input that should be a pointer, we will define it as follows:
func zeroptr(iptr *int) {
In this simple example, we can see two functions, zeroval, which receives the value of the variable i
by copy, and the function zeroptr, which receives it by reference:
package main
import "fmt"
func zeroval(ival int) {
ival = 0
}
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
i := 1
fmt.Println("i value:", i)
zeroval(i)
fmt.Println("i value:", i)
zeroptr(&i)
fmt.Println("i value:", i)
fmt.Println("Memory address i variable:", &i)
}
When running the code, we get the following output:
i value: 1
i value: 1
i value: 0
Memory address i variable: 0x84c01c0a8
We can see that the value of the variable i
in the main function has only been affected when we passed the pointer, as we have turned it into a “shared” variable between the main function and zeroptr.