Monday, March 30, 2015

An Introduction to Go Defer Statement - with Code Example

For various reasons, there could be occasions when you want to delay the execution of a statement or function. Before I bombard you with definition & jargon of defer keyword, let me share a simple self explanatory example.
  • What output will you get after executing the following code snippet?
  • Output of the code is as shown below. 
  • English dictionary meaning of defer = Put off (an action or event) to a later time; postpone

Defer works as expected and as defined above. You can play around with the above example here at Go Playground.

Effective Go defines defer as:

"Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return." 

Practical Uses of Defer Keyword

In practical scenarios defer is used for cleanup operations viz. freeing up resources. Defer guarantees that the deferred statement / function call is performed immediately before the function executing the defer returns.  

I'll share the same example which official docs have shared. Assume, you want to create a file, open a file, write to it, and finally close it. Here you can defer close file function and can can call the close file function, with a defer prefix, immediately after calling the open file function. 

This construct sounds simple with an added advantage that it guarantees that you'll never forget to close the file you've opened.

Another Example

Check the following snippet:
  • What output do you expect from above code?
Always remember the order of execution of deferred functions is LIFO (Last-in-first-out). So, the output is as follows:
You can play with the above example here at Go Playground.

Analogy from Other Languages

The defer keyword is similar to finally block in C# & Java and ensure keyword in Ruby. Share if you know about other similar construct in other languages. 
Hope this article serves well for a golang newcomer. if you liked it, spread the word about it. 

Feel free to share this.