2

I have a simple code for removing element from slice:

package main

import "fmt"

func main() {
    values := []string{"1", "2", "3", "4", "5"}
    valuesResult := removeElementByIndex(values2, 0)
    fmt.Printf("%v - %v\n", values, valuesResult)
}

func removeElementByIndex[T interface{}](a []T, i int) []T {
    return append(a[:i], a[i+1:]...)
}

but output is

[2 3 4 5 5] - [2 3 4 5]

For some reason values are changing, but i didnt change it in my method (i guess). Please help me to fix it

Neighbourhood
  • 166
  • 3
  • 13

1 Answers1

2

You did change the original slice. append operation uses the original slice if the result of the append operation fits into the capacity of the slice.

If you need the original slice unchanged:

func removeElementByIndex[T interface{}](a []T, i int) []T {
    result := make([]T, len(a)-1)
    copy(result,a[:i])
    copy(result[i:],a[i+1:])
    return result
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • `You should add code for bounds checking.` I'm not sure that you should check that i is in range. What do you do in that case? Panic? But the code as it is will panic. (Good answer BTW) – AJR Jun 30 '23 at 01:47
  • Good point. Maybe it is ok as is. – Burak Serdar Jun 30 '23 at 02:17