Go语言中的结构体数组

13

我是Go语言的新手,想要在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)

请帮忙。TIA :)

2个回答

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)
}

如果您对切片的工作方式有点模糊,我肯定会建议您阅读这篇文章


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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接