-2

I am using some code I found online to remove an element from a list:

func Remove(slice []string, s int) []string {
    return append(slice[:s], slice[s+1:]...)
}

but the problem is whenever I use it it duplicates the last item on the list! The following code:

func main() {
    lst := []string{"1", "2", "3"}

    fmt.Println(lst)

    slice.Remove(lst, 1)

    fmt.Println(lst)

}

returns [1, 3, 3].

What am I doing wrong?

crispy
  • 67
  • 2

1 Answers1

0

Please store the or return value from the func.

lst = slice.Remove(lst, 1)

Here is the documentation from go src:

The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)
chanchal1987
  • 2,263
  • 6
  • 29
  • 62