This line:
fruits := [4]string{"apple", "orange", "mango"}
Creates an array, not a slice. It has 4 elements even though you only supplied 3. Output of fmt.Printf("%q", fruits)
:
["apple" "orange" "mango" ""]
Slicing it:
tasty_fruits := fruits[1:3]
Results in:
["orange" "mango"]
Length: obviously 2. Capacity?
The capacity is ... the sum of the length of the slice and the length of the [underlying] array beyond the slice.
Since there is one element after "mango"
in the underlying array, capacity is 2 + 1 = 3
.
Indexing the slice (tasty_fruits
): spec: Index expressions:
For a
of slice type S
: a[x]
- if
x
is out of range at run time, a run-time panic occurs
x
is in range if 0 <= x < len(a)
, otherwise it is out of range. Since len(tasty_fruits)
is 2
, the index 2
is out of range, and therefore runtime panic occurs.
You can't index the slice beyond the length of the slice, even if capacity would allow it. You can only reach the elements beyond the length if you reslice the slice, e.g.:
tasty_fruits2 := tasty_fruits[:3]
tasty_fruits2[2] = "nectarine" // This is ok, len(tasty_fruits2) = 3
fmt.Printf("%q", tasty_fruits2)
Output:
["orange" "mango" "nectarine"]