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
statement in front of a function that you are calling. Essentially, that function will execute 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 does a simple print to the console.
Next, we have two print
statements. The results are interesting....