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条)

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗