Golang defer application rules

1. What is defer

It is a mechanism provided by the Go language for registering delayed calls: to allow functions or statements to be executed after the current function is executed (including the normal end through return or the abnormal end caused by panic).

defer is usually used to open/close connections, lock/release locks, and open/close files.

2. Why use defer

We often use some external resources when programming, such as files, connections, locks, etc., and use defer to close these resources to avoid possible memory leaks.

3. How to use defer

demo1:

func hello(i int) {  
    fmt.Println(i)
}

func main() {  
    i := 5
    defer hello(i)
    i = i + 10
}

demo2:

func main() {
    defer_call()
}

func defer_call()  {
    defer func() {fmt.Println("打印前")}()
    defer func() {fmt.Println("打印中")}()
    defer func() {fmt.Println("打印后")}()

    panic("触发异常")
}

Think about the output of the above code?

There are a few points to note in defer:

  1. The defer after return will not be executed
  2. Defer printing is first in, last out. After a panic occurs, the defer will be executed first and then the panic will be executed.
  3. When defer is in a function, it will be executed before the function is executed, defer fun1(..fun2) func2 will be executed first and then func1 will be executed

Guess you like

Origin blog.csdn.net/coffiasd/article/details/114261584