In this section, you are going to learn how to implement a Go function that returns another function using the Go code of returnFunction.go, which will be presented in three segments.
The first code segment of returnFunction.go is as follows:
package main import ( "fmt" ) func funReturnFun() func() int { i := 0 return func() int { i++ return i * i } }
As you can see from the implementation of funReturnFun(), its return value is an anonymous function!
The second code segment from returnFunction.go contains the following code:
func main() { i := funReturnFun() j := funReturnFun()
In this code, you call funReturnFun() two times and assign its return value, which is a function, to two separate variables named i and j. As you will see in the output of the program, the two variables are totally unrelated to each other.
The last code section of returnFunction.go follows next:
fmt.Println("1:", i()) fmt.Println("2:", i()) fmt.Println("j1:", j()) fmt.Println("j2:", j()) fmt.Println("3:", i()) }
So, in this Go code, you use the i variable three times as i() and the j variable two times as j(). The important thing here is that although both i and j were created by calling funReturnFun(), they are totally independent of each other and share nothing. As a result, although their return values come from the same sequence, they do not interfere with each other in any way.
Executing returnFunction.go will produce the following output:
$ go run returnFunction.go 1: 1 2: 4 j1: 1 j2: 4 3: 9
As you can see from the output of returnFunction.go, the value of i in funReturnFun() keeps increasing and does not become 0 after each call either to i() or j().