看下面的几个例子:
func modifyEle(array []int) {
for i := 0; i < len(array); i++ {
(array)[i] = i
}
fmt.Printf("modify int array len = %d, cap = %d \n", len(array), cap(array))
}
func main() {
array := []int{4, 3, 2, 1, 0}
fmt.Println(array)
fmt.Printf("modify befort array len = %d, cap = %d \n", len(array), cap(array))
modifyEle(array)
fmt.Printf("modify after array len = %d, cap = %d \n", len(array), cap(array))
fmt.Println(array)
}
结果:
[4 3 2 1 0]
modify befort array len = 5, cap = 5
modify in array len = 5, cap = 5
modify after array len = 5, cap = 5
[0 1 2 3 4]
上面这个例子中,slice 可以被修改。 再看一个例子。
func deleteEle(array []int) {
array = array[:1]
fmt.Printf("delete in array len = %d, cap = %d \n", len(array), cap(array))
}
func main() {
array := []int{4, 3, 2, 1, 0}
fmt.Println(array)
fmt.Printf("delete befort array len = %d, cap = %d \n", len(array), cap(array))
deleteEle(array)
fmt.Printf("delete after array len = %d, cap = %d \n", len(array), cap(array))
fmt.Println(array)
}
结果
[4 3 2 1 0]
delete befort array len = 5, cap = 5
delete in array len = 1, cap = 5
delete after array len = 5, cap = 5
[4 3 2 1 0]
在上面这个例子中,删除slice 里的元素好像没成功。 继续看下面的例子
func modifyEle(array []int) {
array = append(array, 1)
for i := 0; i < len(array); i++ {
(array)[i] = i
}
fmt.Printf("modify in array len = %d, cap = %d \n", len(array), cap(array))
}
func main() {
array := []int{4, 3, 2, 1, 0}
fmt.Println(array)
fmt.Printf("modify befort array len = %d, cap = %d \n", len(array), cap(array))
modifyEle(array)
fmt.Printf("modify after array len = %d, cap = %d \n", len(array), cap(array))
fmt.Println(array)
}
这个例子跟第一个很像,但是结果完全不同。
[4 3 2 1 0]
modify befort array len = 5, cap = 5
modify in array len = 6, cap = 10
modify after array len = 5, cap = 5
[4 3 2 1 0]
理解了这三个例子,就完全理解 go slice 了。