Deferring Actions In Golang

Edward Pie
5 min readOct 29, 2017

--

“Tomorrow never comes”, is something we tell lazy souls who love to postpone essentials things in life instead of actually getting things done. Permit me to list some popular wisdom about deferring work until tomorrow:

  • Never put off to tomorrow what can be done today
  • The lazier a man is, the more he plans to do tomorrow
  • Nobody is too young to die tomorrow
  • Tomorrow is the day that idlers get busy

These are beautiful nuggets of wisdom, right? Well, never forget them.

Contrary to this wisdom in real-life Golang gives you tools to defer actions and as counter-intuitive as this sounds, it’s actually a good thing that programmers in other languages long for. Did I just present opposing lines of thought? No!

In summary, I encourage you not to defer in real-life but you can and sometimes should definitely defer actions in golang.

Also, if you love my posts on Golang, then do well to subscribe to my Go Rapidly course on Youtube to get notified of the latest videos I post every other day.

What Is Defer?

Well, defer as the name says, allows you to defer. Am I being recursive? May be not.

In go, the “defer” keyword is used to defer the execution of a statement until the end of the function surrounding this statement. Before I show you a demo, I encourage you to always remember the following:

  • Multiple defer statements are executed in the reverse order; last-in-first-out or LIFO.
  • Parameters to deferred functions are resolved immediately. Yes, remember this one to save yourself some headache.

Show Me De’m Codes

The following sample code has deliberately been made very simple since the ultimate goal in this post is to help you understand the work of “defer” in go. And, it doesn’t take the wisdom of King Solomon to understand what it does, does it? Go’s syntax is so awesome that even pre-adamic beings could understand. Lol!

Very useless go program

I’m too shy to show the output of this program and I think you shouldn’t ask why. Now, let’s turn things around with the defer keyword in go as shown below

Introduced defer keyword on line 9

Can you spot the difference? I added defer at the start of line 9 and all of a sudden our program became worthy of getting it output shown in this post. In other words, it suddenly became post-worthy (lol). Let’s see the output now.

Output of earlier progam

Suuuuurpriiiise!!! Huh, aren’t we supposed to see “Finishing main function” printed at the end of the program? No, because we used defer on line 9 which precedes line 10. The effect of defer on our program is that as the name suggests, it will defer the execution of line 9 until just before the main function (the enclosing function) finishes executing that’s why the output seems surprising.

Let’s defer some more statements. After all, tomorrow shall be the busiest day for all lazy people, ain’t it?

Using multiple defer statements

Can you predict what the output will be? I promise you a lion’s egg if you get this correct. Hint : Do you remember I said multiple defer statements are executed in a last-in-first-out (LIFO) order? Well, let’s see the output now.

Result of using multiple defer statements

Come for the lion’s egg if your guess was right. Uno, because multiple defer statements are executed in LIFO order, line 9 executes before line 8 and line 10 actually executes first because everything before it has been deferred until just before the surrounding function ends.

I Can Defer Now, What’s The Point?

Have you wasted hours debugging your code because you forgot to close a file after reading from or writing to it? Have you forgotten to close a socket connection before? If you have ever suffered similar fate then the defer keyword is your pain-killer. The farther away the statement needed to close a resource is from the preceding statements used to process it, the more probable it is for you to forget to close that resource. And, depending on your OS, this action may be punishable by firing squad.

Ignore the read line under line 8, it’s just golang being to sexy about me not using the variables file and err. (Doing this in real-life will let your code not compile)

using defer to release resource before the end of main

And O, One Last Thing You Need To Know

Do you remember I said arguments passed to deferred functions are evaluated immediately? Well, let’s see an example.

immediate evaluation of parameters

Without any surprise, the program above will print 0 instead of the sum of number from 0 to 9 as we expected from the for loop between lines 11 and 14. The reason is that, on line 8 when we used the defer keyword, the value of sum was 0 since that’s the default value for integers.

Finally, if you love my posts on Golang, then do well to subscribe to my Go Rapidly course on Youtube to get notified of the latest videos I post every other day.

And, that’s the end. Thanks!!!

--

--

Edward Pie

I write code for anything that has the capacity to run code. I love Machine Learning & Computer Vision, am addicted to Python, I adore Golang, Swift & Java.