题1: 阅读下面的代码,写出最后的打印结果
return res 底层实现:
- 返回值 = x, 如果函数中已定义返回变量名, 则该返回变量 = x
- 执行返回
遇到 defer 时 return res 底层实现
- 返回值 = x. 如果函数中已定义返回变量名, 则该返回变量 = x; 如果函数中未指定返回变量名, 则假定返回变量名为 returnValue, 也就有 returnValue = x
- 执行 defer 的函数
- 执行 返回
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 // returnValue = 5;x++;return returnValue
6 // x=5;x++;return x
5 // y=x (y=5);x++;return y
5 // 形参不改变原变量
6 // x=5;x++;return x
5 // y=x (y=5);x++;return y
5 // 形参不改变原变量
题2: 下面代码的输出结果是?(提示:defer注册要延迟执行的函数时该函数所有的参数都需要确定其值)
func calc(index string, a, b int) int {
ret := a + b
fmt.Println(index, a, b, ret)
return ret
}
func main() {
x := 1
y := 2
defer calc("AA", x, calc("A", x, y))
x = 10
defer calc("BB", x, calc("B", x, y))
y = 20
}
A 1 2 3
B 10 2 12
BB 10 12 22
AA 1 3 4
B 10 2 12
BB 10 12 22
AA 1 3 4