Defer and Tracing
This lesson discusses important concepts of deferring and tracing functions in Go.
We'll cover the following...
The defer
keyword
The defer
keyword allows us to postpone the execution of a statement or a function until the end of the enclosing (calling) function. Defer executes something (a function or an expression) when the enclosing function returns. This happens after every return, even when an error occurs in the midst of executing the function, not only a return at the end of the function, but before the }. But why after every return? This happens because the return statement itself can be an expression that does something instead of only giving back 1 or more variables. The defer resembles the finally-block in OO-languages as Java and C#; in most cases, it also serves to free up allocated resources. However, keep in mind that a defer-call is function scoped, while a finally-call is block scoped.
Run the following program to see how defer works.
package mainimport "fmt"func main() {Function1()}func Function1() {fmt.Printf("In Function1 at the top\n")defer Function2() // function deferred, will be executed after Function1 is done.fmt.Printf("In Function1 at the bottom!\n")}func Function2() {fmt.Printf("Function2: Deferred until the end of the calling function!")}
As you can see in the above code, in main
we call Function1
at line 5, so control will transfer to line 8. Line 9 will be executed, and In Function1 at the top will be printed on the screen. At line 10, we defer calling Function2()
with the statement: defer
...