标签:def 连续 参数 class ola lan Golan 外部变量 赋值
遇到经典问题
func mian()  {
	resslice := []int{1, 2, 3, 4}
	for _, v := range resslice {
		fmt.Println(v)
		defer fun1(v)
	}
}
func fun1(value int)  {
	fmt.Println(value)
}
输出结果为
1
2
3
4
4
3
2
1
正常传递参数,值传递,运行到defer时把当时的v值传递给函数,最后结束时按defer规律执行
resslice := []int{1, 2, 3, 4}
	for _, v := range resslice {
		fmt.Println(v)
		defer func() {
			fmt.Println(v)
		}()
	}
改为闭包输出结果为
1
2
3
4
4
4
4
4
for range的内部大概是这样
for_temp := v
len_temp := len(for_temp)
for index_temp = 0; index_temp < len_temp; index_temp++ {
        value_temp = for_temp[index_temp]
        index = index_temp
        value = value_temp
        v = append(v, index)
}
循环前把值复制给 for_temp 然后用同一个变量进行赋值
因为闭包里的非传递参数外部变量值是传引用的,是闭包是地址引用
闭包的v 引用外部变量v,把外部的v地址拷贝了一份,执行到最后v的值是4,所以最后输出为连续的4
标签:def 连续 参数 class ola lan Golan 外部变量 赋值
原文地址:https://www.cnblogs.com/9527s/p/13353899.html