douqiang1910 2018-06-06 15:46
浏览 46
已采纳

Golang数组在结构问题

I have problems using a array of structs inside another struct. The issue is that when I fill the structure with data from JSON data in the function below, it is filled correctly. When I directly try to access the data outside of the loop within a new loop the data is not there. So I guess that I'm filling the copied data structure instead of the reference to it so it's only valid inside the first loop. Though I have tried to allocate memory for it and still the same issue.

I guess that I failed somewhere and need directions. See some comments below in the code snippet.

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
", 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!?
        }
    }
}
  • 写回答

1条回答 默认 最新

  • duannuo4620 2018-06-06 15:59
    关注

    The application is unmarshaling to the variable s defined in the loop. Unmarshal to the slice element instead:

        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
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化