You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言匿名函数变量生命周期与执行逻辑的疑问

Go语言闭包行为问题解答

代码示例

import "fmt"

func main() {
    a := test()
    a()
    a()
}

func test() func() {
    num := 0
    fmt.Println("num in test function", num)
    return func() {
        fmt.Println("num in anonymous function", num)
        num++
        fmt.Printf("square is %v: \n", num*num)
        fmt.Println("=====---====")
    }
}

执行输出

num in test function 0
num in anonymous function 0
square is 1:
=====---====
num in anonymous function 1
square is 4:
=====---====

疑问解答

  1. 为什么test函数里的fmt.Println("num in test function", num)只执行一次?
    你仅在a := test()这一行调用了一次test()函数,此时test函数会完整执行一遍,包含里面的打印语句,执行完成后将匿名函数返回给变量a。后续调用的a()是执行返回的匿名函数,并不会再次触发test函数的执行,所以test里的打印语句只会运行一次。

  2. 为什么匿名函数里的num不会重置为0?
    这是Go语言闭包的核心特性:匿名函数会捕获并持有其父作用域(test函数作用域)中变量num的引用,而非复制它的值。当test函数执行完毕返回匿名函数后,num变量并没有被销毁,而是被返回的匿名函数保留了下来。每次调用a()时,都是在操作同一个num变量,因此它的值会持续累加,不会重置为0。而test函数里的num初始值为0,只是test第一次执行时的初始化操作,之后该变量就被闭包持有并持续修改。

内容的提问来源于stack exchange,提问作者aaryaa9978

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:12:14