繁体   English   中英

Golang数组在结构问题

[英]Golang array in struct issue

我在另一个结构中使用数组结构时遇到问题。 问题是,当我在下面的函数中用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在环路定义。 解组切片元素:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM