Defer and Tracing

This lesson discusses important concepts of deferring and tracing functions in Go.

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.

Get hands-on with 1400+ tech skills courses.