Golang:slice之append时原数组发生变化的问题
使用append可以在slice之后追求元素,例如 nums:=[]int{1,2,3}
result:=append(nums,4)
fmt.Println(result)
这段代码很简单,输出result的值为:[1 2 3 4] 回答这个问题,首先需要了解append函数实现原理: 以下代码用来验证这个问题: func test1() {
nums := []int{1,3}
_ = append(nums[:2],4)
fmt.Println("test1:",nums)
//nums changes because the cap is big enought,the original array is modified.
}
func test2() {
nums := []int{1,3}
c := append(nums[:2],[]int{4,5,6}...)
fmt.Println("test2:",nums)
fmt.Println("cc:",c)
//nums dont't change because the cap isn't big enought.
//a new array is allocated while the nums still points to the old array.
//Of course,the return value of append points to the new array.
}
<完结> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |