【Go】defer

defer

defer

The defer statement will defer execution of the function until the outer function returns

Delayed function will understand job search parameters, but the function will not be called until the outer function returns

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
    var count int = 0

    defer fmt.Printf("world:% d \n", count)

    count += 1

    fmt.Printf("Hello:% d \n", count)
}

Save as helloworld.go, the execution results:

1
2
3
[me @ VM_0_14_centos go] # go run helloworld.go
Hello: 1
world: 0

1.Print Hello first, then print world, indicating that the statement after defer was postponed

2.Hello is 1, because count + = 1, count is already 1.
World is followed by 0, although the print world is deferred, the expression in the print statement is executed earlier

defer stack

Defer deferred function calls are pushed onto a stack

The stack meets the LIFO expectation. When the outer function returns, the LIFO functions are called in sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
    fmt.Println("Counting")

    for i: = 0; i <5; i ++ {
        defer fmt.Println(i)
    }

    fmt.Println("over")
}

Save helloworld.go, the results are as follows

1
2
3
4
5
6
7
8
[me@VM_0_14_centos go]# go run helloworld.go 
Counting
over
4
3
2
1
0
Persist in original technology sharing, your support will encourage me to continue to create!