Home > Backend Development > Golang > Use eight demos to understand the five major features of Go language defer

Use eight demos to understand the five major features of Go language defer

藏色散人
Release: 2023-04-23 17:40:51
forward
1616 people have browsed it

Using the defer keyword in Go language can delay code execution until the end of the function. In development, we often use the defer 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))}
Copy after login

deferThe 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.

Feature 1: Calling order when multiple defers are used: first in, last out

When multiple defer keywords are used, the defer statement declared first is called later. Similar to the "stack" first-in-last-out feature, this feature of defer is also easy to understand. Resources opened by first may be relied upon by subsequent code, so ## It is safe to release after #.

func demo1() {
    for i := 0; i < 5; i++ {
        defer fmt.Println("defer:", i)
    }}// defer: 4// defer: 3// defer: 2// defer: 1// defer: 0
Copy after login
Feature 2: The scope is the current function, and there are different defer stacks under different functions

Run demo2. It can be seen from the results that the first anonymous function and the second anonymous function The order of defer execution of functions does not matter.

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
Copy after login

Feature 3: Function parameters after defer are confirmed at the time of declaration (precalculated parameters)

Run demo3_1, according to the results, we can conclude: defer in

The value of the formal parameter n has been confirmed when is declared, not when is 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
Copy after login
Run demo3_2, why is the final output result of defer here the same as the variable num? Because pointers are used here.

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 defer is 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
Copy after login
Look at demo3_3 again. The variables printed by defer are not passed in through function parameters. The "global variable" num is only obtained when defer

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
Copy after login
Feature 4: return and defer execution order: return first defer then

Run demo4_1, you can find that defer and return are executed at the end of the function, but return is executed before defer;

func demo4_1() (int, error) {
    defer fmt.Println("defer")
    return fmt.Println("return")}// return// defer
Copy after login

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 uses to name the return value
, and the final output result is 7. It has gone through the following processes:

    (First) the variable num is used as the return value, and the initial value is 0;
  1. (Second) Then The variable num is assigned a value of 10;
  2. (Then) when return, the variable num is reassigned a value of 2 as the return value;

  3. (Then) defer is executed after return, and the variable num is obtained for modification, and the value is 7;
  4. (Finally) the variable num is used as the return value, and the final function return result is 7;
  5. func demo4_2() (num int) {
     num = 10
     defer func() {
         num += 5
     }()
    
     return 2}// 7
    Copy after login

  6. Let’s look at another example.
In demo4_3, the function uses

anonymous return value
, and the final result output is 2. The process is as follows:

    Enters the function, and the return value variable is not created at this time;
  1. creates the variable num and assigns the value to 10; When
  2. return, create a function return value variable and assign it a value of 2; you can regard this return value variable as an anonymous variable, or as a, b, c, or d variable ..., but it is not the variable num;
  3. defer, no matter how you modify the variable num, it has nothing to do with the function return value;
  4. Therefore, the final function return result is 2;
  5. func demo4_3() int {
     num := 10
     defer func() {
         num += 5
     }()
    
     return 2}// 2
    Copy after login

    Feature 5: When panic occurs, the declared defer will pop out of the stack and execute

    Run demo5_1, you can see that when panic occurs, Trigger the declared defer to pop out of the stack and then panic. However, the defer declared after the panic will not be executed.

    func demo5_1() {
     defer fmt.Println(1)
     defer fmt.Println(2)
     defer fmt.Println(3)
    
     panic("没点赞异常") // 触发defer出栈执行
    
     defer fmt.Println(4) // 得不到执行}
    Copy after login

    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出栈执行
    
     // ...}
    Copy after login

    Attached

    Full code:

    github.com/newbugcoder/learngo/tre...

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template