Basics

Go defer

Using defer

Go defer delays function calls until surrounding function returns.

Introduction to defer in Go

In Go, the defer statement is used to postpone the execution of a function until the surrounding function returns. This can be useful for tasks such as cleaning up resources, logging, or other operations that should be performed regardless of how the function exits.

How defer Works

When a defer statement is encountered, the deferred function call is pushed onto a stack. The deferred calls are executed in LIFO (Last In, First Out) order when the surrounding function completes. This means the last deferred function is executed first.

In the above example, even though the defer statement is placed after the "Start" print statement, the "Middle" is printed after "End" due to the deferred execution.

Using defer with Functions

Deferred functions are often used to ensure certain operations are performed at the end of a function, such as closing a file or releasing a lock. Consider the following example which uses defer to close a file:

In this example, defer file.Close() ensures that the file is closed when the main function finishes executing, regardless of whether the function exits normally or due to an error.

Multiple defer Calls

You can use multiple defer statements within a function. These deferred calls are executed in the reverse order of their appearance. Consider the following illustration:

In this code, the output will be:

Function Body
Third
Second
First

The order of execution is reversed for the deferred calls, demonstrating the LIFO nature of the defer stack.

Arguments Evaluation in defer

It's crucial to understand that the arguments of a deferred function call are evaluated when the defer statement is executed, not when the function is called. Observe the following example:

In this example, the value of x printed by the deferred function will be 0, even though x is updated to 5 before the function returns. This is because the argument to fmt.Println is evaluated at the time of the defer statement, not at the time of execution.

Common Use Cases for defer

Common use cases for defer include:

  • Releasing resources (e.g., closing files or network connections).
  • Unlocking a mutex.
  • Cleaning up temporary files.
  • Logging exit information.

Using defer helps ensure these actions are not forgotten and are executed even if a function exits early due to an error.

Previous
log