2016-10-25 2 views
3

저는 go to new이고 이동 중에 struct 배열을 만들고 초기화하려고합니다. 내 코드는 다음과 같은 에러가 발생이구조체를 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) 

도와주세요. TIA :

+0

어쩌면 당신은 한번 더 투어를 이용할 수 있을까요?. – Volker

답변

6

당신은 하나 개의 요소 노드의 조각 (빈 노드)로 도시를 초기화하는 일했다. 그것에

당신은 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) 
} 

내가 확실히 this article를 읽고 권하고 싶습니다 슬라이스 작동 방식.

+0

예. 고마워! – Parag

0

이 날

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) 
} 
관련 문제