An example of the use of closures for functions in the Go language

  • 2020-06-01 10:00:32
  • OfStack

Unlike the declaration of variables, the Go language cannot declare another function within a function. So in Go's source files, the function declarations appear in the outermost layer.

"Declaration" is to associate a variable of type 1 with a name.

Go has variables of function type, so you can declare a variable of function type in one function, although you can't declare another function directly in one function. In this case, the function is called closure (closure).

Ex. :


packagemain
 
import"fmt"
 
funcmain(){
    add:=func(baseint)func(int)(int){
        returnfunc(iint)(int){
            returnbase+i
        }
    }
   
    add5:=add(5)
    fmt.Println("add5(10)=",add5(10))
}

The use value of this example, only 1, is probably used to demonstrate the construction and use of closures.

add is a closure because it is a variable of an unnamed function type. Think of it as a closure workshop that returns (produces) a closure based on input. So add5 is a closure that takes 5 as an add parameter.

The declaration of the closure is inside another function, forming a nest. Like the nesting of blocks, the inner variables can mask the outer variables with the same name, and the outer variables can be used directly in the inner layer. For example, the base parameter of add is in the outer layer of the closure returned by return, so its value 5 remains after add is returned and assigned to add5. When add5 is executed, the i parameter can add the base from this outer layer to get the result 15.

Personal understanding:

In fact, the most convenient way to understand closures is to think of closure functions as one class, and one closure function call is to instantiate one class.

You can then see which are "global variables" and which are "local variables" from the class's point of view.

For example, the adder function in the above example returns the function func(int) int

pos and neg respectively instantiate two "closure classes" in which there is a "closure global variable" sum. So that makes sense.

Here's another example:


package main import "fmt" func adder() func(int) int {
     sum := 0
     return func(x int) int {
          sum += x
          return sum
     }
} func main() {
     pos, neg := adder(), adder()
     for i := 0; i < 10; i++ {
          fmt.Println(
               pos(i),
               neg(-2*i),
          )
     }
}

Running returns results:


0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90

This is the combination of a closure in Go, a function, and its associated reference environment.


Related articles: