In Go, parameters to functions are passed only by value.
Go pass parameters by value
In the following example, an integer and a User structure are passed as parameters to functions.
package main
import "fmt"
type User struct {
name string
occupation string
}
func main() {
x := 10
fmt.Printf("inside main %d\n", x)
inc(x)
fmt.Printf("inside main %d\n", x)
fmt.Println("---------------------")
u := User{"Raj", "Engineer"}
fmt.Printf("inside main %v\n", u)
change(u)
fmt.Printf("inside main %v\n", u)
}
func inc(x int) {
x++
fmt.Printf("inside inc %d\n", x)
}
func change(u User) {
u.occupation = "driver"
fmt.Printf("inside change %v\n", u)
}
Output:
inside main 10 inside inc 11 inside main 10 --------------------- inside main {Raj Engineer} inside change {Raj driver} inside main {Raj Engineer}
In the above example, the original values of the x and User struct are not modified.
A copy of the integer value is created. Inside the function, we increment the value of this copy. So the original variable is intact.
func inc(x int) {
x++
fmt.Printf("inside inc %d\n", x)
}