问一下各位: 切片取了messages 的2 ~ 5 也就是 3,4,5 len为3 cap为什么是8 而不是7(去除3,4,5) 或者 messages的容量10 下面是详细的代码 和输出结果
```go
func main() {
// 切片截取
messages := []int { 1,2,3,4,5,6,7,8,9,0 } //创建切片
messages2 := messages [2:5]
printSlice( messages2)
}
func printSlice ( x []int){
fmt.Printf( "len=%d cap=%d slice=%v\n", len(x), cap(x), x )
}
```
![QQ截图20171030174822.jpg](https://static.studygolang.com/171030/83e34df6169c7d47ee133afe9deab30c.jpg)
http://docs.studygolang.com/ref/spec#Slice_types
"The array underlying a slice may extend past the end of the slice. The capacity is a measure of that extent: `it is the sum of the length of the slice and the length of the array beyond the slice`; a slice of length up to that capacity can be created by slicing a new one from the original slice. The capacity of a slice a can be discovered using the built-in function cap(a)."
package main
import (
"fmt"
)
func main(){
s := make([]int, 4, 10)
s1 := s[2:cap(s)]
fmt.Println(len(s1))
}
#3
更多评论
http://docs.studygolang.com/ref/spec#Slice_expressions 看这里的说明
> a[low : high : max]
> it controls the resulting slice's capacity by setting it to max - low
#2