Can Golang anonymous functions return multiple values?

WBOY
Release: 2024-04-13 16:09:02
Original
444 people have browsed it

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) {
    // 函数体
}
Copy after login

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)
Copy after login

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
}
Copy after login

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)
}
Copy after login

Output:

Add: 11
Sub: 9
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!