Essential Go  Suggest an edit

Defer

In a complicated function, it’s easy to forgot to release a resource (e.g. to close a file handle or to unlock a mutex).

You can use defer statement to place code releasing a resource close to code that acquires the resource:

func foo() {
  f, err := os.Open("myfile.txt")
  if err != nil {
    return
  }
  defer f.Close()

  // ... lots of code
}

In the above example, defer f.Close() ensures that f.Close() will be called before we exit foo.

Placing defer f.Close() right after os.Open() makes it easy to audit the code and verify Close is always called. This is especially useful for large functions with multiple exit points.

If deferred code is more complicated, you can use a function literal:

func foo() {
  mutex1.Lock()
  mutex2.Lock()

  defer func() {
    mutex2.Unlock()
    mutex1.Unlock()
  }()

  // ... more code
}

You can use multiple defer statements. They’ll be called in reverse order i.e. defer declared first will be executed last.

Deferred functions are called even if a panic happens.

  ↑ ↓ to navigate     ↵ to select     Esc to close