Wednesday, May 3, 2017

Getting Started with Golang Part 5: Cleanup with defer

Often in code you need to have a cleanup run whenever a function returns. It is usually annoying to have to write the same piece of code everywhere you have to return. For this, go has a special statement called defer. For example let's say you want to open a file and then close it when you are done with it:

file, err := ioutil.ReadFile("/tmp/somefilehere")
if err != nil {
   panic(err) //Panic used here for simplicity in this example
}
defer file.Close()
//Some file operations here

Once all of your file operations are complete and your function exits, the file will be closed - even if you exit with a panic. We can also have multiple defer statements. If we have multiple defers they will be run from last to first. This is done because defers defined later often rely on variables which will be cleaned up by defers defined earlier.

An example of this:



(Note: this demo is through Go playground)