Go defer

Go's defer is commonly used to register delayed function calls (i.e., function calls that are executed later). It is extremely useful in handling tasks such as resource cleanup, lock release, logging, closing file handles, closing database connections, closing network connections, and more. It has the following characteristics:

  1. Last In, First Out (LIFO): If there are multiple defer statements within a function, they are executed in the reverse order they were encountered, with the last defer statement executed first.
  2. Arguments are evaluated immediately and saved: When a variable is passed in a defer statement, Go immediately evaluates the current value of that variable (the value of the variable at that exact moment) and saves it. Along with other defer statements, this forms an action that is pushed onto the stack, and then the actions are executed in LIFO order.
  3. Executed before the return statement: The stack of accumulated defer calls is executed right before the function's return statement is processed.
  4. Executed at function exit: defer can be used to ensure that certain operations are performed when a function exits, even if the function returns early due to an error.
for i := 0; i < 3; i++ {
    defer fmt.Println(i)
}
#2
#1
#0

func main() {
    x := "A"
    defer iprint(x) // directly captures the current value of x, which is "A"  
    
    x = "D"
    defer iprint(x)
    
    x = "B"
    defer iprint(x)
}
func iprint(str string) {
    fmt.Println("Current x is ", str)
}

#Current x is  B
#Current x is  D
#Current x is  A

 

Take a break

πŸ‘‰πŸ‘‰πŸ‘‰ 【BTTH Year EP102】The Four Pavilions Grand Meeting began, Xiao Yan rescued Lin Yan