What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given
A
deferstatement defers the execution of a function until the surrounding function returns.
This example demonstrates defer functionality:
func elapsed(what string) func() {
start := time.Now()
fmt.Println("start")
return func() {
fmt.Printf("%s took %v\n", what, time.Since(start))
}
}
func main() {
defer elapsed("page")()
time.Sleep(time.Second * 3)
}
Out:
start
page took 3s