[go] defer function, usage scenarios, precautions and source code analysis

effect

The defer statement is used to delay the call of the function. Each defer will push a function onto the stack. Before the function returns, the delayed function will be taken out and executed, which can prevent memory leaks caused by forgetting to release resources.

scenes to be used

  1. Lock opening and closing
  2. channel switch
  3. close file
  4. Record function execution time for performance analysis.

Precautions

1. The parameters of the delayed function are determined when the defer statement appears

When a variable is output in the main function defer, if it is modified later, the value of the output variable will not change

2. Deferred function execution is executed in last-in-first-out order, that is, the defer that appears first is executed last

3. The delayed function may manipulate the named return value of the main function

Before the main function returns the variable, defer may still change the value

defer structure

type _defer struct {
    
    
    sp      uintptr   //函数栈指针
    pc      uintptr   //程序计数器
    fn      *funcval  //函数地址
    link    *_defer   //指向自身结构的指针,用于链接多个defer
}

Since deger is followed by a function, the function stack pointer, program counter, and function address required by the function are also required. The difference is that the linkpointer points to itself, which is equivalent to a linked list

work process

Every time defer is encountered, the function will be appended to the head of the linked list, and the functions will be run from the head one by one before reutrn, so the order of defer first come first and then executed

implement function

  • deferproc(): Called at the declaration of defer, which stores the defer function in the linked list of goroutine;
  • deferreturn(): In the return instruction, to be precise, it is called before the ret instruction, which takes the defer out of the goroutine linked list and executes it.

Guess you like

Origin blog.csdn.net/csxylrf/article/details/130649526