[英]Array of struct in Go language
I am new to Go and want to create and initialise an struct array in go. 我是Go的新手,想要在go中创建和初始化struct数组。 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 :) TIA :)
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 := 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)
}
I'd definitely recommend reading this article if you are a bit shaky on how slices work. 如果你对切片的工作方式有点不稳定,我肯定会推荐阅读这篇文章 。
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.