I have the following code:
func TestRemoveElement(t *testing.T) {
nums := []int{3, 2, 2, 3}
result := removeElement(nums, 3)
if result != 2 {
t.Errorf("Expected 2, but it was %d instead.", result)
}
}
func removeElement(nums []int, val int) int {
for i, v := range nums {
if v == val {
nums = append(nums[:i], nums[i+1:]...)
}
}
return len(nums)
}
The statement inside the if
statement is the most popular way of replacing an element in a slice per this answer. But this fails deleting the last element due to i+1
. i.e if a match is found in the last element, i+1
is out of bounds. What better way to replace elements that considers last elements?