切片索引超出范围,但一个空间可用
问题描述:
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'
我正试图弄清切片大小调整的工作原理,并且我有以下示例: p> \ n
包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))
}
code>
编译器抱怨: p>
紧急:运行时错误:索引超出范围
code> pre>
\ n b code>的容量为 3 code>,为什么我不能像 p>
b [2] =那样分配 V'
code> pre>
div>
答
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).