3

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\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!?
        }
    }
}
1
  • Try doing the Unmarshal to s instead of &s. Commented Jun 6, 2018 at 15:56

1 Answer 1

4

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
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I was so close! I tried that one time but then I missed to add by reference. Works fine! Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.