dsnd7200 2015-03-06 06:46
浏览 16
已采纳

Golang延迟澄清

What happened when defer called twice when the struct of that method has been changed?

For example:

rows := Query(`SELECT FROM whatever`)
defer rows.Close()
for rows.Next() { 
  // do something
}
rows = Query(`SELECT FROM another`) 
defer rows.Close()
for rows.Next() {
  // do something else
}

which rows when the last rows.Close() called?

  • 写回答

3条回答 默认 最新

  • douguai4653 2015-03-06 07:33
    关注

    It depends on the method receiver and on the type of the variable.

    Short answer: if you're using the database/sql package, your deferred Rows.Close() methods will properly close both of your Rows instances because Rows.Close() has pointer receiver and because DB.Query() returns a pointer (and so rows is a pointer). See reasoning and explanation below.

    To avoid confusion, I recommend using different variables and it will be clear what you want and what will be closed:

    rows := Query(`SELECT FROM whatever`)
    defer rows.Close()
    // ...
    rows2 := Query(`SELECT FROM whatever`)
    defer rows2.Close()
    

    I'd like to point out an important fact that comes from the deferred function and its parameters being evaluated immedately which is stated in the Effective Go blog post and in the Language Spec: Deferred statements too:

    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. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.

    If variable is not a pointer: You will observe different results when calling a method deferred, depending if the method has a pointer receiver.
    If variable is a pointer, you will see always the "desired" result.

    See this example:

    type X struct {
        S string
    }
    
    func (x X) Close() {
        fmt.Println("Value-Closing", x.S)
    }
    
    func (x *X) CloseP() {
        fmt.Println("Pointer-Closing", x.S)
    }
    
    func main() {
        x := X{"Value-X First"}
        defer x.Close()
        x = X{"Value-X Second"}
        defer x.Close()
    
        x2 := X{"Value-X2 First"}
        defer x2.CloseP()
        x2 = X{"Value-X2 Second"}
        defer x2.CloseP()
    
        xp := &X{"Pointer-X First"}
        defer xp.Close()
        xp = &X{"Pointer-X Second"}
        defer xp.Close()
    
        xp2 := &X{"Pointer-X2 First"}
        defer xp2.CloseP()
        xp2 = &X{"Pointer-X2 Second"}
        defer xp2.CloseP()
    }
    

    Output:

    Pointer-Closing Pointer-X2 Second
    Pointer-Closing Pointer-X2 First
    Value-Closing Pointer-X Second
    Value-Closing Pointer-X First
    Pointer-Closing Value-X2 Second
    Pointer-Closing Value-X2 Second
    Value-Closing Value-X Second
    Value-Closing Value-X First
    

    Try it on the Go Playground.

    Using a pointer variable the result is always good (as expected).

    Using a non-pointer variable and using pointer receiver we see the same printed results (the latest) but if we have value receiver, it prints 2 different results.

    Explanation for non-pointer variable:

    As stated, deferred function including the receiver is evaluated when the defer executes. In case of a pointer receiver it will be the address of the local variable. So when you assign a new value to it and call another defer, the pointer receiver will be again the same address of the local variable (just the pointed value is different). So later when the function is executed, both will use the same address twice but the pointed value will be the same, the one assigned later.

    In case of value receiver, the receiver is a copy which is made when the defer executed, so if you assign a new value to the variable and call another defer, another copy will be made which is different from the previous one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料