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 [].
textTagRelationshipsisnil.var thing []typegives younilof type[]type.thing := make([]type, len)gives you an slice of type[]typeand lengthlen, andvar thing [len]typegives you a len-length array of type[]typefilled with the zero value fortype.