I think the question is pretty clear once you look at the following setup?
config := database.NewConfig()
connection := database.Connect(config)
defer connection.Destroy()
...
err = app.Listen(address)
if err != nil {
connection.Destroy() // Do i need this?
panic(err)
}
... // defer connection.Destroy() is called
Do i have to call the deferred function in an error case of panic(err) because thats in a new block and therefore in a different scope?
>Solution :
Do i have to call the deferred function in an error case of
panic(err)because thats in a new block and therefore in a different scope?
No, for two reasons: (1) defer operates at the level of the function, not the level of the block (so in this respect it differs from the scope of local variables); and (2) the invocation happens whenever the surrounding function returns, even if it’s "returning" only because it called some function that ended up panicking.
As the specification puts it:
A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.
(In particular, note that the bit about panicking has to do with the goroutine panicking, rather than worrying about exactly which function triggered the panic.)
I recommend bookmarking the specification and consulting it when you have this sort of question; although parts of it are technical, for the most part it’s pretty readable.