An array of structures in Go

I am new to Go and want to create and initialize a 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 :)

+5
source share
2 answers

You initialize the cities as a slice of nodes with one element (empty node).

You can initialize it to a fixed size using cities := make([]node,47) , or you can initialize it to an empty slice and append to it:

 cities := []node{} for i := 0; i<47 ;i++ { n := node{name: strconv.Itoa(i), children: map[string]int{}} cities = append(cities,n) } 

I would definitely recommend reading this article if you are unsteady about how slicers work.

+8
source

It 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) } 
0
source

Source: https://habr.com/ru/post/1258734/


All Articles