如何在Golang中初始化嵌套结构数组的值 [英] How to initialize values for nested struct array in golang
问题描述
我的结构
type Result struct {
name string
Objects []struct {
id int
}
}
为此初始化值
func main() {
var r Result;
r.name = "Vanaraj";
r.Objects[0].id = 10;
fmt.Println(r)
}
我收到此错误.紧急:运行时错误:索引超出范围"
I got this error. "panic: runtime error: index out of range"
该如何解决?
推荐答案
首先,我要说的是,为您的结构定义类型是更习惯的做法,而不管该结构多么简单.例如:
Firstly, I'd say it's more idiomatic to define a type for your struct, regardless of how simple the struct is. For example:
type MyStruct struct {
MyField int
}
这意味着将您的 Result
结构更改如下:
This would mean changing your Result
struct to be as follows:
type Result struct {
name string
Objects []MyStruct
}
程序出现恐慌的原因是,您试图访问内存中尚未分配的区域( Object
s数组中的一项).
The reason your program panics is because you're trying to access an area in memory (an item in your Object
s array) that hasn't been allocated yet.
对于结构数组,这需要使用 make
完成.
For arrays of structs, this needs to be done with make
.
r.Objects = make([]MyStruct, 0)
然后,为了安全地添加到数组中,最好实例化单个 MyStruct
,即
Then, in order to add to your array safely, you're better off instantiating an individual MyStruct
, i.e.
ms := MyStruct{
MyField: 10,
}
然后将其附加到您的 r.Objects
数组
And then append
ing this to your r.Objects
array
r.Objects = append(r.Objects, ms)
有关 make
的更多信息,请参见文档
For more information about make
, see the docs
这篇关于如何在Golang中初始化嵌套结构数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!