[踩坑]slice引用类型的一个小坑
大家都知道slice是一个引用类型,废话不多说,上代码
func test(res [][]int) {
res[0] = []int{2,2,2,2}
res[1][0] = 3
}
func main() {
res := [][]int{[]int{1,1,1,1},[]int{2,2,2,2}}
test(res)
fmt.Printf("%#v",res)
// out: [][]int{[]int{2, 2, 2, 2}, []int{3, 2, 2, 2}}
}
因为slice是引用类型,所以在函数中的修改也会体现回原宿主
但,如果你在函数中使用了append,那结果就完全不一样了
func test(res [][]int) {
res = append(res, []int{3,3,3,3})
res = append(res, []int{4,4,4,4})
}
func main() {
res := [][]int{[]int{1,1,1,1},[]int{2,2,2,2}}
test(res)
fmt.Printf("%#v",res)
// out: [][]int{[]int{1, 1, 1, 1}, []int{2, 2, 2, 2}}
}
因为append会返回一个新的数组,所以不会体现回原宿主 这里是个坑哦 如果需要在其他函数内涉及到append老老实实用指针吧
Songzhibin

浙公网安备 33010602011771号