背景
在测试中发现了一个对切片更新失败的现象,简化成如下例子
func main() {
var slice []int = []int{1, 2}
changeSlice(slice)
fmt.Println(slice) }
func changeSlice(intSlice []int) {
intSlice = append(intSlice, []int{100, 200}...)
intSlice[0] = 100
intSlice[1] = 200
}
//输出 [1 2]
可见在其中对slice的更新并不起作用,不是预估的[100 200 100 200]
更新测试
在Go语言中的切片是对数组的抽象,它们利用底层数组来存储数据,我们知道slice的本身是一个引用类型。
他的结构体如下:
type slice struct {
array unsafe.Pointer
len int
cap int
}
当切片作为参数传递是,是值传递,也就是传递的原切片的拷贝,而可见在结构体中array是一个指针,指向的是底层数组的地址,在函数中对该切片的操作会影响到原始切片。
通过写一个简单的例子测试一下
func main() {
var slice []int = []int{1, 2}
changeSlice(slice)
fmt.Println(slice)
}
func changeSlice(intSlice []int) {
intSlice[0] = 100
intSlice[1] = 200
}
//输出: [100 200]
在这里的更新是成功的,而在最开始的例子中,对原切片的更新是失败的。
通过前面介绍我们知道changeSlice这个函数接收到的是slice的指针信息,若更新失败则说明在changeSlice中没有拿到正确的地址,可通过进一步的测试看函数调用中的地址变化
func main() {
var slice []int = []int{1, 2}
fmt.Printf("before change: %p\\n", slice)
changeSlice(slice)
fmt.Printf("after change: %p\\n", slice)
}
func changeSlice(intSlice []int) {
fmt.Printf("receive: %p\\n", intSlice)
intSlice = append(intSlice, []int{100, 200}...)
fmt.Printf("after append: %p\\n", intSlice)
intSlice[0] = 100
intSlice[1] = 200
}
// 输出:
before change: 0xc0000a4950
receive: 0xc0000a4950
after append: 0xc0000a2780
after change: 0xc0000a4950
可以很明显看到在after append后,slice的地址发生了变化,在changeSlice中对切片的操作均是基于新的地址后操作的,说明问题出在append这个方法中
// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
// slice = append(slice, elem1, elem2)
// slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
// slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type
通过进一步查看append方法的定义可以发现,在切片有足够的容量时候,会在原切片的末尾追加元素,当没有足够容量的时候,会分配一个新的底层数组复制原有切片的元素并添加新元素,最后返回的是一个新的地址。
那么可知在changeSlice中对原切片进行扩容后实际操作的是一个新的切片,并不会反映到原有切片中。
总结
在通过函数调用更新切片时,应该通过指针的方式进行调用,保证对切片的更新会反映到原切片中,若在函数中出现扩容操作,可能会导致产生一个新的地址导致更新失败。
同样地,我们在对切片进行操作时,应该注意到切片的底层使用的是指针,同样会出现类似更新问题的还有在切片在进行切割的时候会创建原始切片的一个浅拷贝或者重新切片以获取原始切片的一部分,对其的更新操作也会反映到原有切片中。
func main() {
var slice []int = []int{1, 2, 3, 4}
slice1 := slice[0:2]
slice1[0] = 5
fmt.Println(slice)
}
// 输出
[5 2 3 4]