How to use closure functions in the Go language?

In the Go language, a closure function refers to a function that has access to variables in its outer scope. Closure functions can pass variables as parameters or return values to achieve specific functionalities.

Here is an example of a simple closure function.

func main() {
    // 定义匿名函数并赋值给变量add
    add := func(x, y int) int {
        return x + y
    }

    // 调用闭包函数
    result := add(3, 5)
    fmt.Println(result) // 输出:8
}

In the example above, we defined an anonymous function and assigned it to the variable ‘add’. This function can access variables x and y in its outer scope and return their sum. By calling the ‘add’ function with parameters 3 and 5, we get the result 8.

Closure functions can also be used to implement function factories, which means returning a function inside a function. Here is an example:

func adder() func(int) int {
    sum := 0
    return func(x int) int {
        sum += x
        return sum
    }
}

func main() {
    // 调用函数工厂,返回一个闭包函数
    a := adder()

    // 调用闭包函数
    fmt.Println(a(1)) // 输出:1
    fmt.Println(a(2)) // 输出:3
    fmt.Println(a(3)) // 输出:6
}

In the example above, we defined an adder function that returns a closure function. The variable sum inside the closure function will maintain its state with each call. By calling the adder function, we get a closure function a, then we call the a function with different parameters and finally output the results. It can be seen that each time the a function is called, the variable sum will retain its previous accumulated result.

bannerAds