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 = 1000
	fmt.Printf("testdefer4 i=%d \n", i)
}

func main() {
	testdefer1()
	testdefer2()
	testdefer3()
	testdefer4()
}

输出:

aaaaaaaaaaaa
bbbbbbbbbbbb
hello defer V3
hello defer V2
hello defer
running
return
i=4
i=3
i=2
i=1
i=0
testdefer3 i=1000
testdefer3 defer i=0
testdefer4 i=1000
testdefer4 defer i=1000
posted @ 2022-03-06 19:24  ty1539  阅读(95)  评论(0编辑  收藏  举报