Go’s Defer

A defer statement defers the execution of a function until the surrounding function returns.

This is really handy at times! Sure it’s kind of odd because you’re somewhat, ‘hacking the stack’. But it is particularly useful when you need to run some cleanup functions like the closing of files or db connections.


Time for a little debugging snippet!

This allows each function call to wrap logs nicely. This is really nice as it’s easy to add, comment out or remove as it sits at the top of the function:

func foo() {
  defer log.Println("----------")
  // ...