Pass by value or pass by reference
In the official FAQ [1], it says that
As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter. For instance, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to. (See a later section for a discussion of how this affects method receivers.)
We can come up an easy test to see how Go handles pass by value in default and how to pass a pointer to fake pass by reference. The code is shown as follow:
// go run reference.go
package main
import "fmt"
func foo(test int){
test = 1 // change the value to 1
}
func bar(test *int){
*test = 1
}
func main(){
var i = 0
fmt.Println("In main, i is", i)
foo(i)
fmt.Println("After foo call, in main i is", i)
bar(&i)
fmt.Println("After bar call, in main i is", i)
}
You should see the following result.
In main, i is 0
After foo call, in main i is 0
After bar call, in main i is 1