5.9.defer语句

这里将自己学习Go及其区块链的一些笔记、积累分享一下,如果涉及到了文章、文字侵权,请联系我删除或调整。


defer语句用于设置在函数临返回前需要完成的最后任务,如关闭文件等。

func foo() {
    ...
    defer bar()
    ...
}

当函数执行到return语句或到达函数结尾处的右花括号时,先调用defer语句后面的函数(例如bar()),然后再返回。注意,执行defer语句时并不调用bar函数,而只是"记住"稍后再调用它。在go语言中常使用defer语句来提前设定函数返回前需要的“善后操作”。

1. 当函数中包含多条defer语句时,在该函数即将返回前,按照这些defer语句在源代码中出现顺序的逆序依次调用其所指定的函数。

// 通过defer语句指定函数临返回前最后执行的操作
package main

import "fmt"

func main() {
    defer fmt.Println("I'm run after the function completes")

    fmt.Println("Hello World!")
}
// 结果:
// Hello World!
// I'm run after the function completes 

// 多条defer语句依其出现顺序的逆序依次被执行
package main

import "fmt"

func main() {
    defer fmt.Println("I'm the 1st defer statement")
    fmt.Println("Hello World!")
    defer fmt.Println("I'm the 2nd defer statement")
    fmt.Println("Hello George!")
    defer fmt.Println("I'm the 3rd defer statement")
    fmt.Println("Hello Go!")
}
// 结果:
// Hello World!
// Hello George!
// Hello Go!
// I'm the 3rd defer statement
// I'm the 2nd defer statement
// I'm the 1st defer statement 

 

上一篇:golang defer关键字使用


下一篇:js标签中原标签与async和defer的区别