golang defer操作理解

package main

import "fmt"

func test1() (x int) {
	//x只是返回值定义为int类型没有赋值 这个输出取的 int 类型默认值
	defer fmt.Printf("in test1 defer: x = %d\n", x)
	x = 1
	return 6
}

func test2() (x int) {
	x = 2
	//x赋值为2 所以打印为2
	defer fmt.Printf("in test2 defer: x = %d\n", x)
	return 6
}

func test3() (x int) {
	//x先赋值为3 后面return为6 相当于重新赋值x为6 defer函数 先运行本身函数后再执行defer函数
	defer func() {
		fmt.Printf("in test3 defer: x = %d\n", x)
	}()
	x = 3
	return 6
}

func test4() (x int) {
	//x赋值为4 后面return为6 相当于重新赋值x为6 defer函数 先运行本身函数后再执行defer函数
	//传参x x为int默认值 所以n打印为0
	defer func(n int) {
		fmt.Printf("in test4 defer x as parameter: x = %d\n", n)
		fmt.Printf("in test4 defer x after return: x = %d\n", x)
	}(x)

	x = 4
	return 6

}

func main() {
	//所有方法返回都为 6
	fmt.Printf("in main test1 return: x = %d\n", test1())
	fmt.Printf("in main test2 return: x = %d\n", test2())
	fmt.Printf("in main test3 return: x = %d\n", test3())
	fmt.Printf("in main test4 return: x = %d\n", test4())
}

 

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页