切片索引超出范围,但有一个空间可用。

huangapple go评论84阅读模式
英文:

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的范围内有效。引用自规范

> 元素可以通过整数索引0len(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).

huangapple
  • 本文由 发表于 2015年4月29日 18:26:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/29940968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定