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 :)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With