The following example prints 12. I can't understand this output. Why did it print 12 and not 11?
func fA() func() int {
i := 0
return func() int {
i
return i
}
}
func main() {
fB := fA()
fmt.Print(fB())
fmt.Print(fB())
}
CodePudding user response:
It is a closure. Basically, the function returned knows the variable defined outside its scope, so when you call fA(), the returned function has i = 0, when you call fB(), it increments the value of i, now i = 1. when you call it again it will increment i again, and now you have i = 2. If you create a new function using fA(), this new function will have a new i. Something like this:
fB := fA()
fC := fA()
fmt.Print(fB())// 1
fmt.Print(fB())// 2
fmt.Print(fC())// 1
fmt.Print(fB())// 3