当前位置:网站首页>Go closure usage example

Go closure usage example

2022-06-25 14:55:00 Morning snail

stay Go In language , Anonymous functions are needless to say , But closures need to be mentioned .
Closure : Capture external variables , It doesn't matter if these captured variables or constants are out of scope , As long as closures are in use , These variables will always exist .
Use closures to achieve division 0 Calculation of the square of natural numbers other than , Each call is required to return the square of the number of calls . The code is as follows :

package main

import "fmt"

func main() {
    
	f := demo()
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println(f())

}

func demo() func() int {
    
	var x int
	return func() int {
    
		x++
		return x * x
	}
}

Output results :

1
4
9
16
原网站

版权声明
本文为[Morning snail]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200517027313.html