英文:
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'的机制”。
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 (
"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)
}
Output:
[{I am First} {I am Second}]
答案2
得分: 1
你创建了一个包含0个元素的切片。访问索引为0
和1
的元素是无效的。你可能想要像这样创建一个切片:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论