What happens to the defer in the code below?
package main
import "net/http"
func main() {
resp, _ := http.Get("http://google.com")
defer resp.Body.Close()
resp, _ = http.Get("http://stackoverflow.com")
defer resp.Body.Close()
}
There are two HTTP GET calls, both return to the same variable. Does defer stack the operation, leading to two Close() calls, or will only one be executed when main() finishes? (if the latter: will that be the first or second defer that gets executed?)
Yes, the
deferdoes stack the reference to the variablerespleading to twoClosecalls. For example, in the following code, thecleanUpfunction is called with two differentAValues:Above code outputs:
Thus even though the value of
ris overwritten, it doesn't lead to overwriting of variable in thedeferstatement.