-3

As I know, defer is usually used to close or free resources. And using defer FUNC () inside the block (function) of the code ensures that FUNC () will call in case of any return from this block(function) or panic in this block (function).

So - how to explain defer behavior in this code: (Example):

package main
import (
  "fmt"
  "errors"
)
func test() error {
  err := errors.New("some error")
  return err
}
func main() {
  if err := test(); err!=nil {
    fmt.Println("ERROR EXIT")
    return
  }
  defer fmt.Println("DEFER EXIT")
  fmt.Println("NORMAL EXIT")
}

I expected to see this:

ERROR EXIT
DEFER EXIT

But got it:

ERROR EXIT

Where am I wrong?

Борис
  • 167
  • 1
  • 6
  • 3
    the defer never runs, so the fmt.Println isn't set up. When the return occurs in the line above there is no defer waiting to happen – Vorsprung Apr 24 '19 at 12:14
  • 1
    Code within a function is executed in the order expressed by that code. You can't expect a `defer` to happen if it was never executed. – JimB Apr 24 '19 at 12:17
  • https://tour.golang.org/flowcontrol/12 – jrwren Apr 24 '19 at 19:07

1 Answers1

4

You return from the main function before the defer statement could be executed, before the fmt.Println() call could be "enqueued".

Change it to:

defer fmt.Println("DEFER EXIT")
if err := test(); err != nil {
    fmt.Println("ERROR EXIT")
    return
}
fmt.Println("NORMAL EXIT")

Then output will be (try it on the Go Playground):

ERROR EXIT
DEFER EXIT
icza
  • 289,344
  • 42
  • 658
  • 630
  • How about this: `func _httpHandler(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), 500) log.Println(remoteIP, "\t",err.Error()) return } defer r.Body.Close() } ` – Борис Apr 24 '19 at 12:44
  • @Борис How about that what? – icza Apr 24 '19 at 12:48
  • sorry - wrong example. – Борис Apr 24 '19 at 13:08
  • found all answers here - http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/#anameclose_http_resp_bodyaclosinghttpresponsebody – Борис Apr 24 '19 at 13:19