Using thedefer
keyword in Go language can delay code execution until the end of the function. In development, we often use thedefer
keyword to complete the aftermath work, such as closing open file descriptors, closing connections, and releasing resources.
func demo0() { fileName := "./test.txt" f, _ := os.OpenFile(fileName, os.O_RDONLY, 0) defer f.Close() contents, _ := ioutil.ReadAll(f) fmt.Println(string(contents))}
defer
The keyword usually follows immediately after the resource opening code to prevent subsequent forgetting to release the resource. The code declared by defer will not actually be executed until the end of the function. Although defer is simple and easy to use,but if you ignore its features, you will face confusion during development. Therefore, I summarized the five major features of defer and gradually introduced the features of defer through 8 demos.
When multiple defer keywords are used, the defer statement declared first is called later. Similar to the "stack"first-in-last-outfeature, this feature of defer is also easy to understand.Resources opened byfirst may be relied upon by subsequent code, so ## It is safe to releaseafter #.
func demo1() { for i := 0; i < 5; i++ { defer fmt.Println("defer:", i) }}// defer: 4// defer: 3// defer: 2// defer: 1// defer: 0
The defer scope is only the current function and is executed at the end of the current function, so there are different defer stacks under different functions.
func demo2() { func() { defer fmt.Println(1) defer fmt.Println(2) }() fmt.Println("=== 新生代农民工啊 ===") func() { defer fmt.Println("a") defer fmt.Println("b") }()}// 2// 1// === 新生代农民工啊 ===// b// a
The value of the formal parameter n has been confirmed whenis declared, notwhenis executed; therefore, no matter how the subsequent variable num changes, it will not affect the output result of defer.
func demo3_1() { num := 0 defer func(n int) { fmt.Println("defer:", n) }(num) // 等同 defer fmt.Println("defer:", num) for i := 0; i < 10; i++ { num++ } fmt.Println(num)}//10//defer: 0
defer
When declaring, the address pointed by the formal parameter p pointer has been confirmed, pointing to the variable num; subsequently the variable num changes. So when deferis executed, the output is the current value of the variable num pointed to by the p pointer.
func demo3_2() { num := 0 p := &num defer func(p *int) { fmt.Println("defer:", *p) }(p) for i := 0; i < 10; i++ { num++ } fmt.Println(*p)}//10//defer: 10
is executed, so the output result of defer is the same as the variable. num is consistent.
func demo3_3() { num := 0 defer func() { fmt.Println("defer:", num) }() for i := 0; i < 10; i++ { num++ } fmt.Println(num)}//10//defer: 10
func demo4_1() (int, error) { defer fmt.Println("defer") return fmt.Println("return")}// return// defer
This is obvious from the output results
, but when the execution order of return and defer and the**function return value**"meet", Many complex scenarios will result.
In demo4_2, the function usesto name the return value
, and the final output result is 7. It has gone through the following processes:
func demo4_2() (num int) { num = 10 defer func() { num += 5 }() return 2}// 7
anonymous return value
, and the final result output is 2. The process is as follows:
func demo4_3() int { num := 10 defer func() { num += 5 }() return 2}// 2
Feature 5: When panic occurs, the declared defer will pop out of the stack and execute
func demo5_1() { defer fmt.Println(1) defer fmt.Println(2) defer fmt.Println(3) panic("没点赞异常") // 触发defer出栈执行 defer fmt.Println(4) // 得不到执行}
It is precisely by using this feature that panic can be captured through recover in defer to prevent the program from crashing.
func demo5_2() { defer func() { if err := recover(); err != nil { fmt.Println(err, "问题不大") } }() panic("没点赞异常") // 触发defer出栈执行 // ...}
Attached
The above is the detailed content of Use eight demos to understand the five major features of Go language defer. For more information, please follow other related articles on the PHP Chinese website!