Pass by Value
In Go, variables are passed by value. This means that when you pass a variable into a function, the function receives a copy of that variable.
Immutability of Original Data
Because the function is working with a copy, it cannot mutate the original data in the caller’s scope.
func main() {
x := 5
increment(x)
fmt.Println(x) // Still prints 5
}
func increment(x int) {
x++ // This only increments the copy
}
Why this matters?
Pass-by-value makes code easier to reason about because you don’t have to worry about a function unexpectedly changing your variables. If you do want a function to modify original data, you would use pointers (which we’ll cover later).