Home >Backend Development >Golang >Can Golang anonymous functions return multiple values?

Can Golang anonymous functions return multiple values?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2024-04-13 16:09:02535browse

Yes, anonymous functions in Go language can return multiple values. Syntax: func(arg1, arg2, ..., argN) (ret1, ret2, ..., retM) { // Function body }. Usage: Use the := operator to receive the return value; use the return keyword to return multiple values.

Golang 匿名函数可以返回多个值吗?

#Can anonymous functions in Go language return multiple values?

Short answer:

Yes, anonymous functions in Go language can return multiple values.

Syntax:

func(arg1, arg2, ..., argN) (ret1, ret2, ..., retM) {
    // 函数体
}

Among them:

  • arg1, arg2, .. ., argN is the parameter list of the anonymous function.
  • ret1, ret2, ..., retM is the return value list of the anonymous function.

Usage:

  1. Use the := operator to receive the return value:
values := func(x, y int) (int, int) {
    return x + y, x - y
}(10, 5)

In the above code, the anonymous function receives two integer parameters x and y, and returns their sum and difference. The := operator assigns the return value of an anonymous function to values variables one by one.

  1. Use the return keyword to return multiple values:
func(x int) (int, int) {
    return x + 1, x - 1
}

Actual case:

Consider the following code:

func main() {
    // 定义一个接收整数并返回其加法和减法结果的匿名函数
    addSub := func(x int) (int, int) {
        return x + 1, x - 1
    }

    // 调用匿名函数并分别将加法和减法结果存储在变量中
    sum, diff := addSub(10)

    fmt.Println("Add:", sum)
    fmt.Println("Sub:", diff)
}

Output:

Add: 11
Sub: 9

The above is the detailed content of Can Golang anonymous functions return multiple values?. 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