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.
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:
:=
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 parametersx
andy
, and returns their sum and difference. The:=
operator assigns the return value of an anonymous function tovalues
variables one by one.
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!