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

示例:闭包的记忆效应

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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)
}

   运行代码后

1
2
3
4
5
6
7
8
9
10
11
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 @   左扬  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
levels of contents
点击右上角即可分享
微信分享提示