defer
The defer statement defers the execution of a function until the surrounding function returns. Let's try to explain this a bit better. Inside a function, you have a defer
in front of a function that you are calling. That function will execute essentially right before the function you are currently inside completes. Still confused? Perhaps an example will make this concept a little clearer:
package main import "fmt" func main() { Â Â defer done() Â Â fmt.Println("Main: Start") Â Â fmt.Println("Main: End") } func done() { Â Â fmt.Println("Now I am done") }
The output for the defer
example is as follows:
Main: Start Main: End Now I am done
Inside the main()
function, we have a deferred function, defer
done()
. Notice that the done()
function has no new or special syntax. It just has a simple print to stdout
.
Next, we have two print statements. The results are interesting. The two print
statements...