【问题标题】:Golang array in struct issue结构问题中的Golang数组
【发布时间】: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

标签: arrays go memory


【解决方案1】:

应用程序正在解组到循环中定义的变量s。改为解组到 slice 元素:

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

【讨论】:

  • 哦,我是如此接近!我试过一次,但后来我错过了通过引用添加。工作正常!谢谢!
猜你喜欢
  • 2015-03-23
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多