13

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

1
  • Array and Slice are different types in Go. You need to change your title to Slice. Commented May 28, 2024 at 23:56

2 Answers 2

33

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<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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.