Home  >  Article  >  Backend Development  >  Execution order and purpose of Golang function defer

Execution order and purpose of Golang function defer

WBOY
WBOYOriginal
2024-06-05 13:10:57543browse

The defer function is used in the Go language to delay the execution of a function call until the function returns, and is called in last-in-first-out (LIFO) order. Its uses include releasing resources, logging, and recovering from exceptions. The later deferred function will be called before the first deferred function.

Golang 函数 defer 的执行顺序和用途

The execution sequence and purpose of defer function in Go language

defer function

defer is a unique keyword in the Go language, which can defer function calls until before the function returns. When the function returns, the deferred functions are called in last-in-first-out (LIFO) order.

Purpose of defer

#defer is mainly used in the following scenarios:

  • Release resources (clean up Operation): Used to release allocated resources, such as file handles, database connections, or locks, before the function exits.
  • Logging: Used to log certain events or errors when the function returns.
  • Recovering exceptions: Used to handle exceptions and perform cleanup operations.

defer's execution order

Delayed function calls are executed in last-in-first-out order when the function returns. This means that the later deferred function will be called before the first deferred function.

Practical case: releasing file handle

package main

import (
    "fmt"
    "os"
)

func main() {
    // defer 语句将函数 os.File.Close() 调用推迟到 main() 函数返回之前执行。
    f, err := os.Open("myfile.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()

    // 使用 defer 可以确保文件句柄在函数返回时始终被关闭。
    fmt.Println("File opened successfully.")
}

Output:

File opened successfully.

Other examples:

  • Logging:

    defer fmt.Println("Function completed.")
  • ##Recover exception:

    func safeOperation() (result, err error) {
      // ...省略业务代码...
      if err != nil {
          // 如果操作失败,记录错误并恢复。
          defer func() {
              fmt.Println("Operation failed with error:", err)
          }()
          return nil, err
      }
      // 操作成功,返回结果。
      return result, nil
    }

The above is the detailed content of Execution order and purpose of Golang function defer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn