go - Slice index out of range but one space is free -
i trying figure out how slice resizing works , have 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 not assign 
b[2] = 'v'      
the index valid in range of 0..len(b)-1. quoting spec:
the elements can addressed integer indices
0throughlen(s)-1.
elements beyond length (but within capacity) unavailable through indexing. can access elements if reslice slice include elements (but within capacity).
Comments
Post a Comment