Golang defer clarification

后端 未结 3 1626
迷失自我
迷失自我 2020-12-28 17:14

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

For example:

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


        
相关标签:
3条回答
  • 2020-12-28 17:53

    Ah I see, the rows always refer to the last one, http://play.golang.org/p/_xzxHnbFSz

    package main
    
    import "fmt"
    
    type X struct {
       A string
    }
    
    func (x *X) Close() {
      fmt.Println(x.A)
    }
    
    func main() {
      rows := X{`1`}
      defer rows.Close()
      rows = X{`2`}
      defer rows.Close()
    }
    

    Output:

    2
    2
    

    So maybe the best way to preserve the object is to pass it to a function: http://play.golang.org/p/TIMCliUn60

    package main
    
    import "fmt"
    
    type X struct {
        A string
    }
    
    func (x *X) Close() {
        fmt.Println(x.A)
    }
    
    func main() {
        rows := X{`1`}
        defer func(r X) { r.Close() }(rows)
        rows = X{`2`}
        defer func(r X) { r.Close() }(rows)
    }
    

    Output:

    2
    1
    
    0 讨论(0)
  • 2020-12-28 17:55

    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.

    0 讨论(0)
  • 2020-12-28 17:59

    Effective Go mentions:

    The arguments to the deferred function (which include the receiver if the function is a method) are evaluated when the defer executes, not when the call executes.

    Besides avoiding worries about variables changing values as the function executes, this means that a single deferred call site can defer multiple function executions

    In your case, the defer would reference the second rows instance.
    The two deferred functions are executed in LIFO order (as mentioned also in "Defer, Panic, and Recover").

    As icza mentions in his answer and in the comments:

    The 2 deferred Close() methods will refer to the 2 distinct Rows values and both will be properly closed because rows is a pointer, not a value type.

    0 讨论(0)
提交回复
热议问题