V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
passMeBy
V2EX  ›  程序员

有没有大佬解释下 Golang 的匿名函数的 defer 问题

  •  
  •   passMeBy · 2019-11-18 14:50:08 +08:00 · 1450 次点击
    这是一个创建于 1592 天前的主题,其中的信息可能已经有所发展或是发生改变。

    package main

    import "fmt"

    func a()(i int) {

    defer func(){
    
    fmt.Println("2:",i)
    
    }()
    
    defer fmt.Println("1:",i)
    
    i++
    
    return 
    

    }

    func main() {

    a()
    

    }

    output:

    1: 0

    2: 1

    匿名函数的 defer 为何是 1,是因为闭包函数共享了作用域的变量?

    5 条回复    2019-11-18 17:35:33 +08:00
    codehz
        1
    codehz  
       2019-11-18 15:03:05 +08:00 via Android   ❤️ 2
    defer 时,(顶层)函数参数是立即求值的,然后匿名函数的话,自然就是用外面的 i 了
    (这种技巧也可以用来统计函数运行时间 defer Count(time.Now())
    ManjusakaL
        2
    ManjusakaL  
       2019-11-18 15:04:29 +08:00   ❤️ 2
    https://golang.org/ref/spec#Defer_statements 其实看下 spec 就明白了

    > Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked
    BOYPT
        3
    BOYPT  
       2019-11-18 15:27:59 +08:00   ❤️ 1
    挺有意义的,比如 defer cancel()后面又有另外一个 xx, cancel := xxx,前面的 cancel 不会被覆盖
    TypeErrorNone
        4
    TypeErrorNone  
       2019-11-18 17:33:44 +08:00
    首先 i = 0
    执行 defer fmt.Println("1:",i),这里是传参操作,把 i=0 传值进去了。
    执行 defer func(){fmt.Println("2:",i)}时,i=1,所以输出 1
    TypeErrorNone
        5
    TypeErrorNone  
       2019-11-18 17:35:33 +08:00   ❤️ 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2024 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:16 · PVG 00:16 · LAX 09:16 · JFK 12:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.