arrays - 结构问题中的 Golang 数组

标签 arrays go memory

我在另一个结构中使用结构数组时遇到问题。问题是当我在下面的函数中用来自 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。反编码到 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
        }
    }

关于arrays - 结构问题中的 Golang 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50724527/

相关文章:

javascript - 如何将项目插入到特定索引处的数组中(JavaScript)

linux - 父进程死亡时自动杀死子进程

c++ - 在 Delphi 中使用 SecureZeroMemory

php - 使用 php ://input 内存耗尽

C中的冷启动代码

c - 使用 **ptr 将多维数组传递给函数

javascript - 有没有更有效的方法来过滤这个对象数组?

java - Guava 表与二维数组

go - 导入的结构用作匿名字段

http - 使用 http.FileServer 处理自定义 404 页面