Go语言学习——defer

defer

package main

import "fmt"

// Go语言中函数的return不是原子操作,在底层分为两步来执行
// 第一步:返回值赋值
// defer
// 第二版:真正的RET返回
// 函数中如果存在defer,那么defer执行的时机是在第一步和第二步之间

func f1() int {
	x := 5
	defer func() {
		x++ // 修改的是x不是返回值
	}()
	return x // 1. 返回值赋值 2. defer 3. 真正的RET指令
}

func f2() (x int) {
	defer func() {
		x++
	}()
	return 5 // 返回值=x
}

func f3() (y int) {
	x := 5
	defer func() {
		x++ // 修改的是x
	}()
	return x // 1. 返回值=y=x=5 2. defer修改的是x 3. 真正的返回
}
func f4() (x int) {
	defer func(x int) {
		x++ // 改变的是函数中x的副本
	}(x)
	return 5 // 返回值=x=5
}

func f5() (x int) {
	defer func(x int) int {
		x++ 
		return x
	}(x)
	return 5 
}

// 传一个x的指针到匿名函数中
func f6() (x int) {
	defer func(x *int) {
		(*x)++ 
	}(&x)
	return 5 // 1. 返回值=x=5 2. defer x=6 3. RET返回
}

func main() {
	fmt.Println(f1()) // 5
	fmt.Println(f2()) // 6
	fmt.Println(f3()) // 5
	fmt.Println(f4()) // 5
	fmt.Println(f5()) // 5
	fmt.Println(f6()) // 6
}

defer面试题

package main

import "fmt"

// defer

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

func main() {
	a := 1
	b := 2
	defer calc("1", a, calc("10", a, b))
	a = 0
	defer calc("2", a, calc("20", a, b))
	b = 1
}

// 1. defer calc("1", a, calc("10", a, b))
// 2. defer calc("1", 1, 3) // "10" 1 2 3
// 3. a = 0
// 4. defer calc("2", a, calc("20", a, b))
// 5. defer calc("2", a, 2) // "20" 0 2 2
// 6. b = 1
// 7. calc("2", a, 2) // "2" 0 2 2
// 8. calc("1", a, 3) // "1" 1 3 4


// 1. a := 1
// 2. b := 2
// 3. defer calc("1", 1, calc("10", 1, 2))
// 4. calc("10", 1, 2) // "10" 1 2 3
// 5. defer calc("1", 1, 3)
// 6. a = 0
// 7. defer calc("2", 0, calc("20", 0, 2))
// 8. calc("20", 0, 2) // "20" 0 2 2
// 9. defer calc("2", 0, 2)
// 10. b = 1
// 11. calc("2", 0, 2) // "2" 0 2 2
// 12. calc("1", 1, 3) // "1" 1 3 4
posted @ 2022-05-15 21:41  寻月隐君  阅读(28)  评论(0编辑  收藏  举报