In the Go docs, the cap is the length of the underlying array, why it's value is not 6?
Because the capacity is not the size of the backing array (there may be special cases when they are equal, but in general they are not). When a slice is created by slicing a backing array, using 0
for the low index (or omitting it), and the array length for the high index (or omitting it), then yes, the capacity will be equal to the array's length.
Spec: Length and capacity:
The capacity of a slice is the number of elements for which there is space allocated in the underlying array.
So the capacity starts at the first element of the slice, and if that is not the same as the first element of the backing array, they won't be equal. This is also stated explicitly in the Tour page you linked:
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
There is also a full slice expression which has the form of:
a[low : high : max]
Where you can control the resulting slice's capacity, you can limit how far future slicing may extend the slice. The max
index may point to an element before the last element of the array.
See this example:
a := [10]int{}
s := a[:] // len=10, cap=10
fmt.Printf("len=%d, cap=%d
", len(s), cap(s))
s = a[2:] // len=8, cap=8
fmt.Printf("len=%d, cap=%d
", len(s), cap(s))
s = a[2:7] // len=5, cap=8
fmt.Printf("len=%d, cap=%d
", len(s), cap(s))
s = a[2:7:8] // len=5, cap=6
fmt.Printf("len=%d, cap=%d
", len(s), cap(s))
Outputs (try it on the Go Playground):
len=10, cap=10
len=8, cap=8
len=5, cap=8
len=5, cap=6