类型为struct的切片访问索引超出范围

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

A slice of type struct access index out of range

问题

我正在尝试使用结构体类型的切片。请看下面的示例代码:

package main

import (
	"fmt"
)

func main() {

	arr := []struct {
		A string
		B string
	}{}

	arr[0].A = "I am"
	arr[0].B = "First"

	arr[1].A = "I am"
	arr[1].B = "Second"

	fmt.Println(arr)

}

当我编译这段代码时,我得到了一个超出范围的错误。为什么会这样?

英文:

I am trying to use slice of type struct. Look at the following sample

package main

import (
	"fmt"
)

func main() {

	arr := []struct {
		A string
		B string
	} {}

	arr[0].A = "I am"
	arr[0].B = "First"

	arr[1].A = "I am"
	arr[1].B = "Second"

	fmt.Println(arr)

}

When I compile this code I've got out of range error. Why?

答案1

得分: 3

你需要将新元素添加到切片中(如果不像FUZxxl答案中所示创建一个数组)。使用命名类型比使用类型字面量更容易。

请参阅“向切片追加和复制元素”和“数组、切片(和字符串):'append'的机制”。

示例play.golang.org

package main

import (
	"fmt"
)

func main() {

	type T struct {
		A string
		B string
	}

	arr := []T{}

	arr = append(arr, T{A: "I am", B: "First"})
	arr = append(arr, T{A: "I am", B: "Second"})

	fmt.Println(arr)
}

输出:

[{I am First} {I am Second}]
英文:

You need to append new elements to your slice (if you don't make an array as in FUZxxl's answer.
It is easier with a named type instead of a type literal.

See "Appending to and copying slices" and "Arrays, slices (and strings): The mechanics of 'append'".

Example <kbd>play.golang.org</kbd>

package main

import (
	&quot;fmt&quot;
)

func main() {

	type T struct {
		A string
		B string
	}

	arr := []T{}

	arr = append(arr, T{A: &quot;I am&quot;, B: &quot;First&quot;})
	arr = append(arr, T{A: &quot;I am&quot;, B: &quot;Second&quot;})

	fmt.Println(arr)
}

Output:

[{I am First} {I am Second}]

答案2

得分: 1

你创建了一个包含0个元素的切片。访问索引为01的元素是无效的。你可能想要像这样创建一个切片:

arr := make([]struct{ A, B string }, 2)

Go语言的切片不会自动扩展以容纳更多的元素。

英文:

You have created a slice with 0 (zero) elements. Access to elements at indices 0 and 1 is invalid. You probably wanted something like this:

arr := make([]struct{ A, B string }, 2)

Go slices do not automatically expand themselves to make room for more entries.

huangapple
  • 本文由 发表于 2014年8月3日 23:47:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/25106347.html
匿名

发表评论

匿名网友

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

确定