Go语言中的结构体数组

huangapple go评论85阅读模式
英文:

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)

请帮忙看看。谢谢! Go语言中的结构体数组

英文:

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&lt;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 Go语言中的结构体数组

答案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&lt;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&lt;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&lt;47 ;i++ {
	city=new(node)
	city.name=strconv.Itoa(i)
	city.children=make(map[string]int)
	cities=append(cities,city)
}

huangapple
  • 本文由 发表于 2016年10月25日 09:12:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/40229880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定