Parameter passing of Go functions
In Go, functions pass parameters by value or reference. Understanding the differences between these two delivery methods is critical to optimizing code performance and avoiding unexpected behavior.
Value passing
When a parameter is passed by value, the function receives a copy of the parameter value. This means that any modification to the parameter value will not affect the original parameter outside the function. Passing by value is useful for immutable types such as int, float64, and string because the original value remains unchanged even if their value is changed within the function.
Code example:
package main import "fmt" func addValue(n int) { n++ } func main() { num := 10 addValue(num) fmt.Println(num) // 输出:10 }
Pass by reference
When parameters are passed by reference, the function receives the parameters the address of. This means that any modification to the parameter value will be reflected on the original parameter outside the function. Passing by reference is useful for mutable types such as arrays, slices, and maps, since we need to modify the original value in the function.
To implement reference passing in Go, you can use pointers (*). A pointer is a reference to the address of a variable.
Code Example:
package main import "fmt" func addValuePtr(n *int) { *n++ } func main() { num := 10 addValuePtr(&num) fmt.Println(num) // 输出:11 }
Practical Example
Consider the following function, which calculates the sum of all numbers in an array of numbers:
func sum(nums []int) int { total := 0 for _, num := range nums { total += num } return total }
If we try to pass an array to this function using pass-by-value, any modifications to the array elements inside the function will not affect the original array outside the function. Instead, we need to use pass-by-reference so that the function can access the original array and modify its elements:
func main() { nums := []int{1, 2, 3, 4, 5} sumPtr(&nums) fmt.Println(nums) // 输出:[6 7 8 9 10] } func sumPtr(nums *[]int) { for i, num := range *nums { (*nums)[i] = num + 1 } }
The above is the detailed content of Parameter passing of golang function. For more information, please follow other related articles on the PHP Chinese website!