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.
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:
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!