我在使用一个结构体数组的时候遇到了问题,这个结构体数组是嵌套在另外一个结构体中。问题是在下面的函数中,当我从JSON数据中填充这个结构体的数据时,它被正确地填充了。但是当我在新的循环内直接尝试访问循环外的数据时,数据就不在那里了。所以我想可能是我填充了复制后的数据结构而不是引用它,因此它只在第一个循环内有效。虽然我已经尝试为它分配内存,但问题仍然存在。
我猜我做错了什么,需要指点。请查看代码片段中的一些注释。
我猜我做错了什么,需要指点。请查看代码片段中的一些注释。
type Spaces struct {
Items []*Space `json:"items"`
}
type Space struct {
Id string `json:"id"`
Messages []Message `json:"items"`
}
type Messages struct {
Items []Message `json:"items"`
}
// spaces are marshalled first so that there is a array of spaces
// with Id set. Then the function below is called.
func FillSpaces(space_id string) {
for _,s := range spaces.Items {
if s.Id == space_id {
// I tried to allocate with: s.Messages = &Messages{} without any change.
json.Unmarshal(f, &s) // f is JSON data
fmt.Printf(" %s := %v\n", s.Id, len(s.Messages))) // SomeId := X messages (everything seems fine!)
break
}
}
// Why is the messages array empty here when it was not empty above?
for _,s := range spaces.Items {
if s.Id == space_id {
fmt.Printf("%v", len(s.Messages))) // Length is 0!?
}
}
}
s
而不是&s
。 - Andy Schweig