suggest change

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 {
  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() {

  defer func() {

  // ... 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.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents