9

So I have a types like this

type TextTagRelationship struct {
  Id int64 `json:"id"`
  TagId int64 `json:"tag_id"`
  TaggedText string `json:"tagged_text"`
  TagName string `json:"tag_name"`
  PageNumber int64 `json:"page_number"`
  Color string `json:"color"`
}

type TextTagRelationships []TextTagRelationship

Now, I have a handler that does something like this

func getTaggedTextForPage(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    pageNumber, err := strconv.ParseInt(vars["pageNumber"], 10, 64)
    check(err)
    defer r.Body.Close()
    rows, err := db.Query("SELECT * from tagged_text WHERE page_number = ?", pageNumber)
    check(err)
    var textTagRelationships []TextTagRelationship
    var textTagRelationship TextTagRelationship
    for rows.Next() {
        //execute sql code here
        textTagRelationships = append(textTagRelationships, textTagRelationship)
    }


    if err := json.NewEncoder(w).Encode(textTagRelationships); err != nil {
        check(err)
    }
}

This works fine if there are actual rows, but when encoding an empty array textTagRelationships, in my response in the chrome console I get a null. Why is this happening? It looks like textTagRelationships is actually a [] and so I would have expected the encoding to encode a [] and my response to have a [].

3
  • 1
    Sounds like textTagRelationships is nil. Commented May 22, 2017 at 18:34
  • well, nothing happens to it. It's just inited. And when I print it out I print out an empty array. Commented May 22, 2017 at 18:36
  • 1
    It's declared, not inited. var thing []type gives you nil of type []type. thing := make([]type, len) gives you an slice of type []type and length len, and var thing [len]type gives you a len-length array of type []type filled with the zero value for type. Commented May 23, 2017 at 13:19

1 Answer 1

13

It looks like this is a gotcha in Go.

https://danott.co/posts/json-marshalling-empty-slices-to-empty-arrays-in-go.html

The solution around this is to not rely on the default init behaviour and actually do a make.

var textTagRelationships TextTagRelationships = make(TextTagRelationships, 0)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.