Passing parameter values
In Go, all parameters passed to a function are done so by value. This means a local copy of the passed values is created inside the called function. There is no inherent concept of passing parameter values by reference. The following code illustrates this mechanism by modifying the value of the passed parameter, val
, inside the dbl
function:
package main import ( "fmt" "math" ) func dbl(val float64) { val = 2 * val // update param fmt.Printf("dbl()=%.5f\n", val) } func main() { p := math.Pi fmt.Printf("before dbl() p = %.5f\n", p) dbl(p) fmt.Printf("after dbl() p = %.5f\n", p) }
golang.fyi/ch05/funcpassbyval.go
When the program runs, it produces the following output that chronicles the state of the p
variable before it is ...
Get Learning Go Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.