I am trying to figure out how slice resizing works and I have the following sample:
package main
import (
"fmt"
)
func main() {
s := []byte{'A', 'W', 'T', 'Q', 'X'}
b := s[2:4]
fmt.Println(s, len(s), cap(s))
fmt.Println(string(b), len(b), cap(b))
b[1] = 'H'
b[2] = 'V'
fmt.Println(string(b))
}
The compiler complains:
panic: runtime error: index out of range
b
has capacity of 3
, why can I not assign like
b[2] = 'V'
The index is only valid in the range of 0..len(b)-1
. Quoting from the spec:
The elements can be addressed by integer indices
0
throughlen(s)-1
.
Elements beyond the length (but within the capacity) are unavailable through indexing. You can only access those elements if you reslice the slice to include those elements (but within the capacity).