Go-12 Golang语言中 函数详解之defer语句的延迟使用

package main

import "fmt"

// Golang函数详解之defer语句的延迟使用

/*	defer语句,Go 语言中的defer语句会将其后面跟随的语句进行延迟处理。先被defer的语句最后被执行,最后被defer的语句,最先被执行	*/

/*	//	defer语句执行案例1,这个多理解理解,这个案例当时没有直接看明白,说明知识点没有领悟透彻啊

func f1() int {
	x := 5
	defer func() {
		x++
	}()
	return x
}
func f2() (x int) {
	defer func() {
		x++
	}()
	return 5
}
func f3() (y int) {
	x := 5
	defer func() {
		x++
	}()
	return x
}
func f4() (x int) {
	defer func(x int) {
		x++
	}(x)
	return 5
}
func main() {
	fmt.Println(f1())
	fmt.Println(f2())
	fmt.Println(f3())
	fmt.Println(f4())
	// 执行结果是
	//	5
	//	6
	//	5
	//	5
}

*/


func calcs(index string, a, b int) int {
	ret := a + b
	fmt.Println(index, a, b, ret)
	return ret
}

func main() {

	/*	1. defer语句执行规则:被defer注册的语句,会按照defer定义的倒序进行执行。
		也就是说,先被defer的语句最后被执行,最后被defer的语句,最先被执行。示例如下:
		fmt.Println("开始啦")
		defer fmt.Println(110)
		defer fmt.Println(120)
		defer fmt.Println(130)
		fmt.Println("结束啦")

		// 执行结果是:
			开始啦
			结束啦
			130
			120
			110

	*/

	// 1.1 defer语句案例1,见上面已注释的地方。

	// 1.2 defer语句案例2
	x := 1
	y := 2
	fmt.Println("start")
	defer fmt.Println(1, x, y)             // 1 1 2
	defer fmt.Println(2, x, y)             // 2 1 2
	defer calcs("AA", x, calcs("A", x, y)) // 内部里面的calcs("A",x,y)未被defer注册会按照代码执行顺序从上到下执行,外部defer注册的calcs()函数会按照defer定义的倒序规则进行执行
	x = 10
	defer fmt.Println(3, x, y)             // 3 10 2
	defer calcs("BB", x, calcs("B", x, y)) // 内部里面的calcs("A",x,y)未被defer注册会按照代码执行顺序从上到下执行,外部defer注册的calcs()函数会按照defer定义的倒序规则进行执行
	fmt.Println("end")
	y = 20
	println(x, y) // 10 20
	/*	执行结果是:
		start
		A 1 2 3    // 注释:这里是calcs("A", x, y)函数的执行
		B 10 2 12    // 注释:这里是calcs("B", x, y)函数的执行
		end
		10 20
		BB 10 12 22
		3 10 2
		AA 1 3 4
		2 1 2
		1 1 2
	*/

}


posted @ 2022-12-09 12:08  大海一个人听  阅读(17)  评论(0编辑  收藏  举报