Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when defer is called twice on same variable?

Tags:

go

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?

like image 860
Kokizzu Avatar asked Mar 06 '15 06:03

Kokizzu


People also ask

Does defer execute before return?

A defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

Is defer executed on panic?

In Go, we use defer, panic and recover statements to handle errors. We use defer to delay the execution of functions that might cause an error. The panic statement terminates the program immediately and recover is used to recover the message during panic.

Can defer change return value?

defer can refer to and change the return values.

How does defer in Golang work?

In Golang, the defer keyword is used to delay the execution of a function or a statement until the nearby function returns. In simple words, defer will move the execution of the statement to the very end inside a function.


3 Answers

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.

like image 200
icza Avatar answered Oct 30 '22 12:10

icza


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.

like image 44
VonC Avatar answered Oct 30 '22 12:10

VonC


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
like image 31
Kokizzu Avatar answered Oct 30 '22 12:10

Kokizzu