Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of struct in Go language

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

like image 987
Parag Avatar asked Oct 25 '16 01:10

Parag


1 Answers

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)
}
like image 162
Parag Avatar answered Sep 21 '22 18:09

Parag