Golang中结构体中的数组问题

3
我在使用一个结构体数组的时候遇到了问题,这个结构体数组是嵌套在另外一个结构体中。问题是在下面的函数中,当我从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!?
        }
    }
}

尝试将“Unmarshal”到s而不是&s - Andy Schweig
1个回答

4
应该将反序列化操作改为将数据解包到循环中定义的变量 ,而不是直接解包到变量 。请将其解包到切片元素中。
    for i, s := range spaces.Items { 
        if s.Id == space_id {
            err := json.Unmarshal(f, &spaces.Items[i]) // <-- pass pointer to element
            if err != nil {
               // handle error
            }
            break
        }
    }

哦,我差点就成功了!我尝试过一次,但是错过了添加引用的步骤。现在它可以正常工作了!谢谢! - nergal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接