Home >Backend Development >Golang >Parameter passing in golang function

Parameter passing in golang function

WBOY
WBOYOriginal
2024-04-28 18:39:02641browse

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

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: Integer, floating point, Boolean, string and other basic types.
  • Reference type: Types such as arrays, slices, structures, pointers, etc. that refer to actual data.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn