切片长度是切片中元素的数量。切片容量是所引用数组中,从切片起始索引开始到数组结尾的元素数。
让我们来看一些例子。
package main
import (
"fmt"
)
func main() {
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
fruitslice := fruitarray[1:3]
fmt.Printf("length of slice %d capacity %d", len(fruitslice), cap(fruitslice)) //切片长度为2,容量为6
}
在上面的程序中,切片是由水果数组的索引1和2创建的,切片长度是2,容量是6。
一个切片可以被重新切片,但不能超出它的容量,否则就会抛出运行时错误。
package main
import (
"fmt"
)
func main() {
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
fruitslice := fruitarray[1:3]
fmt.Printf("length of slice %d capacity %d\n", len(fruitslice), cap(fruitslice)) //长度为2,容量为6
fruitslice = fruitslice[:cap(fruitslice)] //重新切片
fmt.Println("After re-slicing length is",len(fruitslice), "and capacity is",cap(fruitslice))
}
切片被重新切片,新切片的结束索引是源切片的容量,以上程序输出:
length of slice 2 capacity 6
After re-slicing length is 6 and capacity is 6