Go从入门到精通——函数——示例:闭包的记忆效应

示例:闭包的记忆效应

  闭包对它作用域上部变量的引用可以进行修改,修改运用的变量就会对变量进行实际修改。

  被捕获到闭包中的变量让闭包本身拥有了记忆效应,闭包中的逻辑可以修改闭包捕获的变量,变量会跟随闭包声明周期一直存在,闭包本身就如同变量一样拥有了记忆效应。

package main

import "fmt"

//提供一个值,每次调用函数会指定对值进行累加
func Accumulate(value int) func() int {

	//返回一个闭包
	return func() int {

		//累加
		value++

		//返回一个累加
		return value
	}
}

func main() {

	//创建一个累加器,初始值为1
	accumulator := Accumulate(1)

	fmt.Println(accumulator())
	fmt.Println(accumulator())

	//打印累加器的函数地址
	fmt.Printf("%p \n", accumulator)

	//创建一个累加器,初始值为1
	accumulator2 := Accumulate(10)

	//累加1并发音
	fmt.Println(accumulator2())

	//打印累加器的函数地址
	fmt.Printf("%p \n", accumulator2)
}

   运行代码后

Starting: D:\go-testfiles\bin\dlv.exe dap --check-go-version=false --listen=127.0.0.1:54125 from d:\go-testfiles
DAP server listening at: 127.0.0.1:54125
Type 'dlv help' for list of commands.
2
3
0x9b5a80 
11
0x9b5a80 
Process 10268 has exited with status 0
Detaching
dlv dap (7624) exited with code: 0

 

posted @ 2022-05-28 14:36  左扬  阅读(46)  评论(0编辑  收藏  举报
levels of contents