How to call golang function

PHPz
Release: 2024-04-21 09:21:01
Original
541 people have browsed it

There are two ways to call functions in Go: value passing and reference passing. Passing by value passes a copy of the variable to the function without affecting the value of the original variable; passing by reference passes the address of the variable to the function, and any modification will affect the value of the original variable. In actual combat, the Add function uses value passing, and the Multiply function uses reference passing to modify the value of the variable in different ways.

How to call golang function

Go function calling method

In the Go language, function calling can be implemented in two ways: value passing and reference passing.

Value passing

Value passing passes a copy of a variable to a function, which means that any modifications within the function will not affect the value of the original variable.

package main

import "fmt"

func add(x int) int {
    x++  // 修改 x 的副本
    return x
}

func main() {
    y := 5
    newY := add(y)  // 传递 y 的副本
    fmt.Println(newY)  // 输出 6
    fmt.Println(y)  // 输出 5
}
Copy after login

Pass by reference

Pass by reference passes the address of a variable to a function, which means that any modifications to the variable within the function will affect the value of the original variable.

package main

import "fmt"

func add(x *int) {
    *x++  // 修改 x 指向的值
}

func main() {
    y := 5
    add(&y)  // 传递 y 的地址
    fmt.Println(y)  // 输出 6
}
Copy after login

Practical case

In the following code, we define two functions: Add and Multiply. Add is passed by value, while Multiply is passed by reference.

package main

import "fmt"

func Add(x int) {
    x++
}

func Multiply(x *int) {
    *x *= 2
}

func main() {
    a := 5
    Add(a) // 调用 Add,使用值传递
    fmt.Println(a) // 输出 5(值不变)

    b := 10
    Multiply(&b) // 调用 Multiply,使用引用传递
    fmt.Println(b) // 输出 20(值已修改)
}
Copy after login

The above is the detailed content of How to call golang function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template