Previous index: juejin.cn/post/695390…

A, defer

1. The role

  • Statements decorated with the defer keyword are deferred until the function is about to return

  • Defer is often used to close the file descriptor, close the database connection, and unlock the resource after the function call

  • When there are multiple defer statements, the order of execution is similar to the stack in the data structure, with first in, then out

Code examples:

package main
import "fmt"

func deferDemo(a){
	fmt.Println("start")
	defer fmt.Println("defer1")//defer defer this statement until the function is about to return
	defer fmt.Println("defer2")// Multiple defer executions, similar to stacks in data structures, advance in and then out
	defer fmt.Println("defer3")
	fmt.Println("end")}func main(a){
	deferDemo()
 }
Copy the code

2. Defer executes the order in the return

In Go, instead of an atomic operation, the return statement is split into two steps:

package main
import "fmt"

func f1(x int,y int) int{
	return x+y
}

func main(a){
	f1()
 }
Copy the code
  1. The return value is equal to x+y;
  2. Ret instruction

The defer statement executes between these two steps:

  1. The return value is equal to XXX
  2. defer
  3. Ret instruction

To further explain, consider the following example:

package main

func f(a) int {
    i := 5
    defer func(a) {
        i++
    }()
    return i
}

func f1(a) (result int) { 
    defer func(a) { 
        result++ 
    }() 
    return 0
}

func f2(a) (r int) { 
    t := 5 
    defer func(a) { 
        t = t + 5} ()return t
}

func main(a) {
    println(f())
    println(f1())
    println(f2())
}
Copy the code

Output result:

5 1Copy the code

Explanation:

For f(), return 5(where I is 5), defer, I ++(I becomes 6), return 5;

For f1(), which returns result, defer,result++,result changes to 1, and return result (1);

For f2(), the return value is r (at this point r equals t, which is 5), and defer, where t becomes 10, and r (5) is returned.