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...