Golang defer clarification

后端 未结 3 1628
迷失自我
迷失自我 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: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.

提交回复
热议问题