While writing program in Golang I wanted to remove an element under arbitrary idx of a slice and preserve ordering. Here’s the signature
func removeOrdered(slice []byte, idxToRemove) []slice
Initially I wanted to make a function that just loops through all the elemenents after the removed idx and shifts them one index down. But I’ve found a nice alternative by Jon doing the same but using more idiomatic Go in first answer here:
How to delete an element from a Slice in Golang
Just for reference here’s the suggested implementation:
func remove(slice []int, s int) []int {
return append(slice[:s], slice[s+1:]...)
}
However it seems to me that there’s a problem with that implementation. It produces
panic: runtime error: slice bounds out of range
when trying to delete the last entry.
Correct me if I’m wrong.
Let’s expand the original function a bit:
func remove(slice []int, s int) []int {
restOfTheSlice := slice[s+1:]
return append(slice[:s], restOfTheSlice...)
}
Let’s now suppose argument is a slice of 8 elements. It’s last valid idx 7. So restOfTheSlice
starts at idx 7+1=8 which is out of bounds.
Anyway can somebody propose something better/more idiomatic or should I fall back to my original plan?