英文:
Array of struct in Go language
问题
我是你的中文翻译助手,以下是你的代码的翻译:
我刚开始学习Go语言,想要创建和初始化一个结构体数组。我的代码如下:
type node struct {
name string
children map[string]int
}
cities := []node{node{}}
for i := 0; i < 47; i++ {
cities[i].name = strconv.Itoa(i)
cities[i].children = make(map[string]int)
}
我得到了以下错误信息:
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0xa6800, 0xc42000a080)
请帮忙看看。谢谢!
英文:
I am new to Go and want to create and initialise an struct array in go. My code is like this
type node struct {
name string
children map[string]int
}
cities:= []node{node{}}
for i := 0; i<47 ;i++ {
cities[i].name=strconv.Itoa(i)
cities[i].children=make(map[string]int)
}
I get the following error:
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0xa6800, 0xc42000a080)
Please help. TIA
答案1
得分: 33
你正在将城市初始化为一个只有一个元素(一个空节点)的切片。
你可以使用cities := make([]node, 47)
将其初始化为固定大小,或者你可以将其初始化为空切片,并使用append
进行添加:
cities := []node{}
for i := 0; i < 47; i++ {
n := node{name: strconv.Itoa(i), children: map[string]int{}}
cities = append(cities, n)
}
如果你对切片的工作原理有些摸不着头脑,我强烈推荐阅读这篇文章。
英文:
You are initializing cities as a slice of nodes with one element (an empty node).
You can initialize it to a fixed size with cities := make([]node,47)
, or you could initialize it to an empty slice, and append
to it:
cities := []node{}
for i := 0; i<47 ;i++ {
n := node{name: strconv.Itoa(i), children: map[string]int{}}
cities = append(cities,n)
}
I'd definitely recommend reading this article if you are a bit shaky on how slices work.
答案2
得分: 6
这对我有用
type node struct {
name string
children map[string]int
}
cities:=[]*node{}
city:=new(node)
city.name=strconv.Itoa(0)
city.children=make(map[string]int)
cities=append(cities,city)
for i := 1; i<47 ;i++ {
city=new(node)
city.name=strconv.Itoa(i)
city.children=make(map[string]int)
cities=append(cities,city)
}
英文:
This worked for me
type node struct {
name string
children map[string]int
}
cities:=[]*node{}
city:=new(node)
city.name=strconv.Itoa(0)
city.children=make(map[string]int)
cities=append(cities,city)
for i := 1; i<47 ;i++ {
city=new(node)
city.name=strconv.Itoa(i)
city.children=make(map[string]int)
cities=append(cities,city)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论