Question: 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?

Answer: 
[Effective Go](https://golang.org/doc/effective_go.html#defer) 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](http://blog.golang.org/defer-panic-and-recover)").

As [icza](https://stackoverflow.com/users/1705598/icza) mentions in [his answer](https://stackoverflow.com/a/28894103/6309) and [in the comments](https://stackoverflow.com/questions/28893586/golang-defer-clarification/28893673?noredirect=1#comment46052483_28893673):

> 
> 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.
> 
> 
>
Most of the time, you should be able to just add a block, that way you don't have to worry about thinking of a new variable name, and you don't have to worry about any of the items not being closed:

```
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
   }
}

```

<https://golang.org/ref/spec#Blocks>