英文:
Slice index out of range but one space is free
问题
我正在尝试弄清楚切片调整大小的工作原理,并且我有以下示例代码:
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))
}
编译器报错:
panic: runtime error: index out of range
b
的容量为 3
,为什么我不能像下面这样赋值:
b[2] = 'V'
请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。
英文:
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'
答案1
得分: 3
索引只在0..len(b)-1
的范围内有效。引用自规范:
> 元素可以通过整数索引0
到len(s)-1
进行访问。
超出长度但在容量范围内的元素无法通过索引访问。只有在将切片重新切片以包含这些元素(但在容量范围内)时,才能访问这些元素。
英文:
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
through len(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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论