1024programmer Java Go closure program interpretation

Go closure program interpretation

package main

 import "fmt"

 //The following function is a closure function (a function that returns the address of an anonymous function, which requires 1. defining a local variable i that needs to be protected 2. an anonymous function) to implement the counting function
 func Counter() func() int {
     i := 0
     res := func() int {
         return i

     fmt.Println("Counter internal:", res) //0x49d5d0 is the address of the anonymous function res is the anonymous function func() int
     fmt.Printf("%T\n", res) //The type of res is the function form func() int
     fmt.Printf("%T\n", res()) //res() is to execute an anonymous function, and the return value after execution is 1 (int)

     fmt.Println("res():", res()) //The reason why the print is 2 is that res() executes an anonymous function. Once executed, the variables in the anonymous function are calculated once and the variables are not cleared after running.
     fmt.Println("res():", res()) //This is the third time running function res()
     return res //The Counter function returns the address of the anonymous function


 func main() {

     res1 := Counter() //Execute Counter() and assign the return value to res1, which is the func() int type variable
     fmt.Printf("%T\n", res1) // res1 := Counter() res1 is the function name, res1 = func()int
     fmt.Printf("%T\n", res1()) // res1() is to execute func()int anonymous function, then the return is Int
     fmt.Println("res1():", res1) // The printed address is the same as above
     fmt.Println("res1():", res1()) //This is the fifth time to run the function res() 5
     fmt.Println("res1():", res1()) //This is the 6th time to run the function res() 6

     res2 := Counter()
     fmt.Println("res2():", res2) // The memory address does not change and is consistent with res1
     fmt.Println("res2():", res2()) //But the closure function was re-entered, so the i variable was reassigned from 0
     fmt.Println("res2():", res2())

Technical pictures

go closure program interpretation

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/734681

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top