Removing an element from a slice duplicates the last element in Go?

Issue

I was playing with slices in go to better understand the behaviour.
I wrote the following code:

func main() {
    // Initialize
    myslice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
    newSlice := myslice

    fmt.Println(myslice)
    fmt.Println(newSlice)

    removeIndex := 3
    newSlice = append(newSlice[:removeIndex], newSlice[removeIndex+1:]...)
    fmt.Println(myslice)
    fmt.Println(newSlice)


}

This is the output:

[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]

[1 2 3 5 6 7 8 9 9]
[1 2 3 5 6 7 8 9]

I dont really understand what happens with newSlice that duplicates the 9 at the end. Also, does this mean, that this operation removes the given element from the underlying array?

https://go.dev/play/p/pf7jKw9YcfL

Solution

The append operation simply shifts the elements of the underlying array. newSlice and mySlice are two slices with the same underlying array. The only difference is the length of the two: After append, newSlice has 8 elements, and mySlice still has 9 elements.

Answered By – Burak Serdar

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.