SoFunction
Updated on 2025-03-04

A detailed explanation of the Defer mechanism in Go language

In Go, defer is a keyword that ensures the cleanup and release of resources, especially resources created in functions. The defer statement will defer the subsequent function call until the function containing it is executed when it is about to return. This makes defer an ideal choice for handling resource cleaning operations such as file closure, database connection release, unlocking, etc.

How Defer works

The defer statement will put its function call into a delayed call stack. When the function is executed and exited, these delayed functions will be executed in the order of the last-in-first-out (LIFO). This means that the function that is deferred will be executed first.

Features of Defer

Delayed execution: The function call after defer will be delayed until the function containing it is about to return.

Last in first out: If there are multiple defer statements, their execution order is last in first out.

Parameter evaluation: The parameters of the defer statement are evaluated when defer, not when executed.

Defer's example

Here is an example using defer that shows how to ensure that the file is closed correctly before the function exits, even if an error occurs while writing to the file.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Open a file	file, err := ("", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
	if err != nil {
		("Error opening file:", err)
		return
	}

	// Use defer to ensure that the file is closed before the function exits	defer ()

	// Write data to file	_, err = ("Hello, World!\n")
	if err != nil {
		("Error writing to file:", err)
		return
	}

	("Data written to file successfully.")
}

Code explanation

Open File: Use Open or create a file, if it fails to open, print an error and return.

Defer statement: defer () ensures that the file is closed before the function exits. Regardless of whether the file write operation is successful or not, () will be executed.

Write file: Use write data to the file. If the write fails, print an error and return.

Multiple calls to Defer

If there are multiple defer statements, their execution order is back in first out. Here is an example showing the execution order of multiple defer statements:

package main

import "fmt"

func main() {
	("main start")

	defer func() {
		("defer 1")
	}()

	defer func() {
		("defer 2")
	}()

	("main end")
}

Output

main start
main end
defer 2
defer 1

Output explanation

main start: The function starts executing.

main end: The function body has been executed.

defer 2: The second defer statement is executed first.

defer 1: Execute after the first defer statement.

This example clearly shows the last-in-first-out execution order of the defer statement.

Defer best practices

Resource cleaning: Use defer to close files, database connections, and release locks.

Avoid abuse: Don't use defer for normal function calls, it should be used for actions that must be performed when the function exits.

Pay attention to parameter evaluation: Since the defer parameters are evaluated when defer, you need to pay attention to the life cycle and side effects of the parameters.

By using defer rationally, you can ensure the correct management and release of resources, improving the robustness and maintainability of your program.

This is the end of this article about a detailed explanation of the Defer mechanism in Go language. For more related contents of the Go Defer mechanism, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!