Categorygithub.com/fakorede/learning-golanggo-functions03-function-and-method-expressions04-stateful-functions
package
0.0.0-20200526015148-b343531734ec
Repository: https://github.com/fakorede/learning-golang.git
Documentation: pkg.go.dev
# README
Stateful Function
func powerOfTwo() func() int64 {
x := 1.0
return func() int64 {
x++
return int64(math.Pow(x, 2))
}
}
Everytime the function is called, x is updated.
func main() {
p2 := powerOfTwo()
value := p2()
fmt.Println(value) // 4
value = p2()
fmt.Println(value) // 9
value = p2()
fmt.Println(value) // 16
}