[英]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.