go的defer用法
作者:互联网
注意:testdefer3() defer 与testdefer4() defer匿名函数 的区别,这是易错点
点击查看代码
package main
import (
"fmt"
)
// defer在函数返回的时候执行,多用于资源释放(打开文件,打开数据库连接,函数返回之后,关闭连接)
func testdefer1() {
defer fmt.Println("hello defer")
defer fmt.Println("hello defer V2")
defer fmt.Println("hello defer V3") // 多个defer执行顺序是后进先出的栈列
fmt.Println("aaaaaaaaaaaa")
fmt.Println("bbbbbbbbbbbb")
}
func testdefer2() {
for i := 0; i < 5; i++ {
defer fmt.Printf("i=%d\n", i)
}
// 打印顺序 4,3,2,1,0
fmt.Println("running ")
fmt.Println("return")
}
func testdefer3() {
var i int = 0
defer fmt.Printf("testdefer3 defer i=%d\n", i) // 在i=0时,已经写入defer中了
i = 1000
fmt.Printf("testdefer3 i=%d \n", i)
}
func testdefer4() {
var i int = 0
defer func(){
fmt.Printf("testdefer4 defer i=%d\n", i) // 在i=0时,已经写入defer中了
}()
i = 1000
fmt.Printf("testdefer4 i=%d \n", i)
}
func main() {
//testdefer1()
//testdefer2()
testdefer3()
testdefer4()
}
testdefer3() testdefer4()输出:
点击查看代码
testdefer3 i=1000
testdefer3 defer i=0
testdefer4 i=1000
testdefer4 defer i=1000
标签:Println,defer,func,fmt,用法,testdefer3,testdefer4,go 来源: https://www.cnblogs.com/heris/p/15973103.html