Home  >  Article  >  Backend Development  >  How are golang function parameters passed?

How are golang function parameters passed?

WBOY
WBOYOriginal
2024-06-02 16:57:41327browse

There are two ways to pass function parameters: value passing and reference passing. Pass-by-value copies a copy of the parameter value, and modifications to the copy do not affect the original value. Pass-by-reference passes a reference to the parameter value, and modifications to the value pointed to by the reference will affect the original value. Practical example: Swap the elements of two string slices using the swapStringslice() function passed by reference.

How are golang function parameters passed?

Passing function parameters in Go

In the Go language, function parameters can be passed by value or by reference.

Value passing

Value passing refers to passing a copy of the parameter value to the function. This means that any modifications to the copy of the parameter will not affect the original value.

func swap(a, b int) {
    var tmp = a
    a = b
    b = tmp
}

func main() {
    x := 10
    y := 20
    swap(x, y)
    fmt.Printf("x=%d,y=%d\n", x, y) // x=10,y=20
}

Passing by reference

Passing by reference means passing a reference to a parameter to a function. This means that any modification to the value pointed to by the parameter reference affects the original value.

To implement reference passing in Go, you need to use pointer types as function parameters.

func swap(a, b *int) {
    var tmp = *a
    *a = *b
    *b = tmp
}

func main() {
    x := 10
    y := 20
    swap(&x, &y) // 注意此处使用指针
    fmt.Printf("x=%d,y=%d\n", x, y) // x=20,y=10
}

Practical case

The following is a practical case using reference passing:

Implement a swapStringslice() function, This function swaps the elements of two string slices.

package main

import "fmt"

func swapStringslice(a, b *[]string) {
    var tmp = *a
    *a = *b
    *b = tmp
}

func main() {
    x := []string{"a", "b", "c"}
    y := []string{"d", "e", "f"}
    swapStringslice(&x, &y)
    fmt.Println(x, y) // [d e f] [a b c]
}

The above is the detailed content of How are golang function parameters passed?. 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