Multiple defers vs deferred anonymous function

Vlad Didenko picture Vlad Didenko · Sep 12, 2015 · Viewed 15.9k times · Source

Is it safer or more idiomatic to issue multiple defer statements which are dependent on the order, or to defer an anonymous function which packages the logic?

Examples:

defer os.Remove(tempFile.Name())
defer tempFile.Close()

In the case above the syntax is minimal, yet the order of defers is reverse to the logic to be executed.

In the case below there are more lines, more "syntax", but the logic is in a more natural order:

defer func() {
    tempFile.Close()
    os.Remove(tempFile.Name())
}()

Which one to use?

Answer

Ross Light picture Ross Light · Sep 12, 2015

In this example, the anonymous function is easier to read, especially once you add in error handling.

f, err := ioutil.TempFile("", "prefix")
if err != nil {
  log.Println("creating temp file:", err)
  return
}
defer func() {
  err := f.Close()
  if err != nil {
    log.Println("close:", err)
  }
  err = os.Remove(f.Name())
  if err != nil {
    log.Println("remove:", err)
  }
}()

If you have multiple resources, then multiple defers is generally appropriate.