What is the use of defer in golang? Language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given function?
解决方案
We use defer to close or deallocate resources usually. It is guaranteed to run in every case. In case of any return or panic. You don't have this guarantee when you just place the function at the end.
Moreover a deffered function call can handle panic by calling recover builtin function. This cannot be done by function at the end.
You can think of it as another implementation of try-catch-finally blocks.
Closing alike try-finally
func main() {
f, err := os.Create("file")
if err != nil {
panic("cannot create file")
}
defer f.Close()
// no matter what happens here file will be closed
// for sake of simplicity I skip checking close result
fmt.Fprintf(f,"hello")
}
Closing and panic handling alike try-catch-finally
func main() {
defer func() {
msg := recover()
fmt.Println(msg)
}()
f, err := os.Create(".") // . is a current directory
if err != nil {
panic("cannot create file")
}
defer f.Close()
// no matter what happens here file will be closed
// for sake of simplicity I skip checking close result
fmt.Fprintf(f,"hello")
}
The benefit over try-catch-finally is that there is no nesting of blockes and variable scopes that simplifies structure of the function.
Alike finally blocks, deferred function calls can also modify returned value if the reach the returned data.
func yes() (text string) {
defer func() {
text = "no"
}()
return "yes"
}
func main() {
fmt.Println(yes())
}