go defer特点

  • 后进先出原则
  • 报错也不会阻断defer输出
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    func test_error(x int) {
    result := 100 / x
    fmt.Println("result = ", result)
    }
    func main() {
    defer fmt.Println("aaaaaaaaaaaaaaaa")
    defer fmt.Println("bbbbbbbbbbbbbbbb")
    //调用一个报错函数
    defer test_error(0)
    defer fmt.Println("cccccccccccccccc")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Running] go run "d:\go work\test.go"
cccccccccccccccc
bbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaa
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.test_error(0x7961f0)
d:/go work/test.go:9 +0xad
main.main()
d:/go work/test.go:26 +0x132
exit status 2

[Done] exited with code=1 in 1.094 seconds

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!