// from https://www.liwenzhou.com/posts/Go/09_function/
package main
import (
"log"
)
func f1() int {
x := 5
defer func() {
x++ //修改的是x,不是返回值
}()
return x //没有在写返回值, return x 相当于 匿名的返回值=x,执行RET时,返回值是5
}
func f2() (x int) {
defer func() {
x++
}()
return 5 //返回值x=5,defer 改的x,执行RET ,结果是6
}
func f3() (y int) {
x := 5
defer func() {
x++
}()
return x //第一步 返回值 y=x=5, 第二步 defer修改x , 第三步,执行RET
}
func f4() (x int) {
defer func(x int) {
x++
log.Println("x in f4 defer func(x int)=====>",x) //1
}(x)
return 5 //第一步 x=5 , 第二步 defer 修改的是形参,不是传给匿名函数的x,第三步执行RET
}
func f5() (x int) {
defer func(x int)int {
x++
log.Println("in f5 defer x ===>",x)
return x //没人接受
}(x)
return 5 // 第一步 x=5 , 第二步
}
func main() {
log.Println(f1())
log.Println(f2())
log.Println(f3())
log.Println(f4())
log.Println(f5())
}
//2021/02/06 23:07:21 5
//2021/02/06 23:07:21 6
//2021/02/06 23:07:21 5
//2021/02/06 23:07:21 x in f4 defer func(x int)=====> 1
//2021/02/06 23:07:21 5
//2021/02/06 23:07:21 in f5 defer x ===> 1
//2021/02/06 23:07:21 5
原文:https://www.cnblogs.com/eiguleo/p/14383490.html