Home >Backend Development >Golang >What is defer in Go? how to use?

What is defer in Go? how to use?

藏色散人
藏色散人forward
2021-09-01 15:52:432574browse

This article is introduced to you by the go language tutorial column. The topic is about the learning and use of go defer. I hope it will be helpful to friends in need!

What is defer?

In Go, a function call can follow a defer keyword to form a deferred function call.
When a function call is delayed, it will not be executed immediately. It will be pushed into a deferred call stack maintained by the current coroutine. When a function call (which may or may not be a deferred call) returns and enters its exit phase, all deferred calls that have been pushed within this function call will be executed in reverse order of the order in which they were pushed onto the stack. When all these delayed calls are executed, the function call actually exits.
A simple example:

package mainimport "fmt"func sum(a, b int) {
    defer fmt.Println("sum函数即将返回")
    defer fmt.Println("sum函数finished")
    fmt.Printf("参数a=%v,参数b=%v,两数之和为%v\n", a, b, a+b)}func main() {
    sum(1, 2)}

output:

参数a=1,参数b=2,两数之和为3
sum函数finished
sum函数即将返回

In fact, each coroutine maintains two call stacks.

  • One is a normal function call stack. In this stack, two adjacent calls have a calling relationship. Calls that are placed on the stack late are called by calls that are placed on the stack early. The earliest call pushed in this stack is the start call of the corresponding coroutine.
  • The other stack is the delayed call stack mentioned above. There is no call relationship between any two calls in the deferred call stack.

defer function parameter valuation

  • For a delayed function call, its actual parameters are the values ​​that are called when this function is called. Evaluated when pushed into the deferred call stack.
  • The expressions in an anonymous function body will be evaluated one by one when the function is executed, regardless of whether the function is called normally or delayed.
    Example 1:
package mainimport  "fmt"func  Print(a int) {fmt.Println("defer函数中a的值=", a)}func  main() {a := 10defer  Print(a)a = 1000fmt.Println("a的值=", a)}

output:

a的值= 1000
defer函数中a的值= 10

defer Print(a) When it is added to the delayed call stack, the value of a is 5, so defer Print(a ) The output result is 5
Example 2:

package mainimport "fmt"func main() {
    func() {
        for i := 0; i < 3; i++ {
            defer fmt.Println("a=", i)
        }
    }()

    fmt.Println()
    func() {
        for i := 0; i < 3; i++ {
            defer func() {
                fmt.Println("b=", i)
            }()
        }
    }()}

output:

a= 2
a= 1
a= 0

b= 3
b= 3
b= 3

i in the first anonymous function loop is pushed into the delayed call stack during the fmt.Println function call The value estimated when , so the output result is 2, 1, 0. i in the second anonymous function is the value estimated during the exit phase of the anonymous function call (i has become 3 at this time), so the output result is: 3, 3,3.
In fact, by slightly modifying the second anonymous function call, you can make it output the same result as the anonymous function one:

package mainimport "fmt"func main() {
    func() {
        for i := 0; i < 3; i++ {
            defer fmt.Println("a=", i)
        }
    }()

    fmt.Println()
    func() {
        for i := 0; i < 3; i++ {
            defer func(i int) {
                fmt.Println("b=", i)
            }(i)
        }
    }()}

output:

a= 2
a= 1
a= 0

b= 2
b= 1
b= 0

Panic and recovery(defer recover)

Go does not support exception throwing and catching, but it is recommended to use return values ​​to explicitly return errors. However, Go supports a similar mechanism to exception throwing/catching. This mechanism is called the panic/recover mechanism.

We can call the built-in function panic to generate a panic so that the current coroutine enters a panic state.

Entering a panic condition is another way to cause the current function call to start returning. Once a function call generates a panic, the function call will immediately enter its exit phase, and the deferred calls pushed onto the stack within the function call will be executed in reverse order of the order in which they were pushed.

By calling the built-in function recover within a delayed function call, a panic in the current coroutine can be eliminated, allowing the current coroutine to re-enter normal conditions.

Before a coroutine in panic exits, the panic will not spread to other coroutines. If a coroutine exits in a panic condition, it will crash the entire program. Look at the following two examples:

package mainimport (
    "fmt"
    "time")func p(a, b int) int {
    return a / b}func main() {
    go func() {
        fmt.Println(p(1, 0))
    }()
    time.Sleep(time.Second)
    fmt.Println("程序正常退出~~~")}

output:

panic: runtime error: integer pide by zero

goroutine 6 [running]:
main.p(...)
        /Users/didi/Desktop/golang/defer.go:9
main.main.func1()
        /Users/didi/Desktop/golang/defer.go:14 +0x12
created by main.main
        /Users/didi/Desktop/golang/defer.go:13 +0x39exit status 2

p function panics (divisor is 0), because the coroutine does not have a panic recovery mechanism, causing the entire program to crash.
If the coroutine where the p function is located is added with panic recovery (defer recover), the program can exit normally.

package mainimport (
    "fmt"
    "time")func p(a, b int) int {
    return a / b}func main() {
    go func() {
        defer func() {
            v := recover()
            if v != nil {
                fmt.Println("恐慌被恢复了:", v)
            }
        }()
        fmt.Println(p(1, 0))
    }()
    time.Sleep(time.Second)
    fmt.Println("程序正常退出~~~")}

output:

恐慌被恢复了: runtime error: integer pide by zero
程序正常退出~~~

For more golang related knowledge, please visit the golangtutorial column! ##

The above is the detailed content of What is defer in Go? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete