【发布时间】:2018-06-06 15:46:41
【问题描述】:
我在另一个结构中使用结构数组时遇到问题。问题是当我在下面的函数中用来自 JSON 数据的数据填充结构时,它被正确填充。当我直接尝试在新循环中访问循环外的数据时,数据不存在。所以我想我正在填充复制的数据结构而不是对它的引用,所以它只在第一个循环内有效。虽然我试图为它分配内存,但仍然是同样的问题。
我猜我在某个地方失败了,需要指导。见下面代码sn-p中的一些cmets。
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!?
}
}
}
【问题讨论】:
-
尝试将
Unmarshal改为s而不是&s。