Im pretty new in GoLang and i need some help. Im making simple API app.
pasing structs by API to slice looks like this:
type Struct struct {
//some records
}
var structs []Struct //slice
func SetStruct(w http.ResponseWriter, req *http.Request) {
var st Struct
decoder := json.NewDecoder(req.Body)
decoder.Decode(&st)
emails = append(structs, st)
json.NewEncoder(w).Encode(structs)
}
And that function works ok.
Second thing i want to do, is to deleting that structs from slice depends on NR
parametr. I call it POST
. Method looks like this:
func SendStruct(w http.ResponseWriter, req *http.Request) {
var st Email
decoder := json.NewDecoder(req.Body)
decoder.Decode(&st)
for i, item := range emails {
if item.NR == st.NR {
structs = append(structs[:i], structs[i+1:]...)
//if numbers match, delete from slice emails
}
}
json.NewEncoder(w).Encode(emails)
}
And it works pretty ok when i have scenerio like (for example):
{"NR": "22"}
{"NR": "33"}
{"NR": "22"}
When i want to delete "33"
, it works pretty ok. When i want to delete "22"
(both of them) things starts to be complicated, because when i pass 22
, app crashes.
In item.NR
(from SendStruct
) i get variable out of range. When i add break
paarmetr in for
, it works ok but i can only deleting structs one-by-one. I want to delete all 22
in one API call. Error that i get:
http: panic serving [::1]:52163: runtime error: slice bounds out of range
Thanks for any advices!
You shouldn't modify slices while you're iterating over them. The range
doesn't know that the slice is now shorter than it was when it started, so eventually it tries to iterate beyond that point and -- whoops! -- there's no more slice to be found.
What I'd recommend doing instead is keeping a separate slice with a list of indexes where the item to be deleted can be found. Then, when you're done iterating over the email slice, you can iterate over this index-tracker slice and delete the relevant items. Make sure you sort the index-tracker slice so that it goes from high indexes to low indexes or you'll end up shortening the slice relative to where the remaining index points are.