Home >Backend Development >Golang >Parameter passing in golang function
The parameter passing of GoLang function adopts the pass-by-value mechanism. Modification of value type parameters does not affect the actual parameters, while modification of reference type parameters will affect the actual parameters; pointer parameters allow indirect access and modification of the actual parameters.
Parameter passing in GoLang function
Introduction
In GoLang, Parameter passing follows the pass-by-value mechanism. This means that any changes made to the parameters inside the function will not affect the actual parameters outside the function.
Parameter type
The parameters of the GoLang function can be value types or reference types.
Value type
For value type parameters, any modification to the parameters inside the function will not affect the actual parameters. This is because during a function call, a copy of the parameters is created.
func swap(a, b int) { a, b = b, a // 在函数内交换 a 和 b 的副本 } func main() { x := 5 y := 7 swap(x, y) fmt.Println(x, y) // 输出 5 7 }
Reference type
For reference type parameters, modifications to the parameters inside the function will affect the actual parameters. This is because the function operates directly on the actual data.
func swap(a, b []int) { a[0], b[0] = b[0], a[0] // 交换切片的第一个元素 } func main() { x := []int{5} y := []int{7} swap(x, y) fmt.Println(x, y) // 输出 [7] [5] }
Pointer
The pointer type provides a mechanism for indirect access to values. When passing a reference type through a pointer, the actual parameters can be modified.
func swap(a, b *int) { *a, *b = *b, *a // 交换指针指向的值 } func main() { x := 5 y := 7 swap(&x, &y) fmt.Println(x, y) // 输出 7 5 }
Practical case
The following is a practical case using function parameter passing:
type Book struct {
The above is the detailed content of Parameter passing in golang function. For more information, please follow other related articles on the PHP Chinese website!