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 0 through len(s)-1.

elements beyond length (but within capacity) unavailable through indexing. can access elements if reslice slice include elements (but within capacity).


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -