DEV Community

Atharva Chidambar Joshi
Atharva Chidambar Joshi

Posted on • Originally published at toothsy.hashnode.dev on

All you need to know about defer & closure in Go-Lang

cant really begin the article without the mascot

Hello, fellow internet user, before we begin, this article assumes you have the following pre-requisites

  • You know about functions in go

  • have an understanding of the local and global scope

  • Have your vsc setup for go-lang, because itll be a delightful experience with autocomplete, linting and auto-imports

With that out of the way, onto the main issue at hand, young padawan.

Just what is defer all about?

Just so we're on the same page, you always use defer keyword on a function call. Now what defer means is that the execution of the deferred function is delayed till the end of the surrounding function.

  • One thing to note is that if you have multiple defer keywords in a single function, they will be executed in First In Out Last, or FILO order, in simple words, the reverse order in which they were deferred.

  • Let's go a little crazy for a second and add defer keyword to everything you see, try predicting the output.

  • Things to note, the deferred function belongs to the surrounding function and not the block scope, so if you deferred a function in an if block, or a for loop, the deferred function will always execute after the surrounding function ends, not before the loop or if statement.

Okay, but what if I wanted to return something from a deferred function?

  • well, you can't do it, your function needs to be the kind that returns nothing, or you can have a return and choose to defer it but you'll have to ignore the return value.

  • But go has this feature called named return, which makes things a little interesting.

Okay now for closures

  • Closures are function values that reference variables residing outside of the function in question.

  • This piece of code is shamelessly stolen from the go docs because it is actually that effective to understand.

let's mix things up!!

  • it gets more interesting when you defer an anonymous function in a loop, as the function loses its meaning outside the scope of the loop, the compiler has to keep track of the deferred function calls in different ways, have a look below.

  • but in the other loop, in line 17, we store the value that index holds along with the function, as dictated by the docs here,

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

Hope you learned something from this article, if there are any incorrect assumptions made on my behalf, please do tell :), nothing would delight me more than dispelling my inaccurate understandings.

Meanwhile, I'll just link the things that helped me write this article

Thanks for reading and hope you have a great day 😁

Top comments (0)