Home >Backend Development >Golang >Golang anonymous function and closure principle analysis
Yes, anonymous functions in Go can be used to quickly define one-time functions or functions that are executed immediately, while closures are used to block local variables in the anonymous function so that these variables can be accessed even if the latter returns.
Anonymous functions are functions that are defined directly without defining a function name. They are often used to define one-time functions, or functions that need to be executed immediately. Syntax:
func() { // 函数体 }
Closure is a technique that "locks" local variables in an anonymous function so that local variables can be accessed even after the anonymous function returns. This can be achieved by using an anonymous function as the return value of another function or method. Syntax:
func makeCounter() func() int { count := 0 return func() int { count++ return count } }
The following code uses anonymous functions and closures to generate a function that generates random numbers:
package main import ( "fmt" "math/rand" "time" ) func main() { // 创建一个匿名函数,生成一个随机数 randomFunc := func() int { rand.Seed(time.Now().UnixNano()) return rand.Intn(100) } // 将匿名函数包装在一个闭包中,封锁随机数生成器 getRand := func(r func() int) func() int { return func() int { return r() } }(randomFunc) // 生成 10 个随机数并打印 for i := 0; i < 10; i++ { fmt.Println(getRand()) } }
Output:
32 78 15 64 12 99 17 42 5 37
The above is the detailed content of Golang anonymous function and closure principle analysis. For more information, please follow other related articles on the PHP Chinese website!