Will two defer calls for the same function be both executed?

1k Views Asked by At

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?)

1

There are 1 best solutions below

10
Sai Ravi Teja K On

Yes, the defer does stack the reference to the variable resp leading to two Close calls. For example, in the following code, the cleanUp function is called with two different A Values:

package main

import "fmt"

type Resp struct {
    A int
}

func (r *Resp) cleanUp() {
    fmt.Println("Cleaned up ", r.A)
}

func main() {
    r := &Resp{1}   
    defer r.cleanUp()   
    
    fmt.Println("I am doing something here!")

    r = &Resp{2}
    defer r.cleanUp()
}

Above code outputs:

I am doing something here!
Cleaned up  2
Cleaned up  1

Thus even though the value of r is overwritten, it doesn't lead to overwriting of variable in the defer statement.