Sobes.tech
Middle+

```go import ( "fmt" ) func deleteElement(s []int, idx int) []int { return append(s[:idx], s[idx+1:]...) } func main() { all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println("Original slice: ") fmt.Println(" all: ", all) //---123--- del := deleteElement(all, 5) fmt.Println("After deleting element with idx = 5: ") fmt.Println(" all: ", all) //--- fmt.Println(" del: ", del) // fmt.Println("After del[0] = 999 and del[len(del) - 2] = 998: ") del[0] = 999 del[len(del)-2] = 998 fmt.Println(" all: ", all) //--- fmt.Println(" del: ", del) // } ```

sobes.tech AI

Answer from AI

In this example, the deleteElement function removes an element from the slice s at index idx using append(s[:idx], s[idx+1:]...).

It is important to understand that slices in Go are structures containing a pointer to an array, a length, and a capacity. When using append, the underlying array may be reused if the capacity allows.

In your example:

  • all is an initial slice of 10 elements.
  • del := deleteElement(all, 5) creates a new slice that points to the same underlying array but without the element at index 5.

After modifying elements in del (del[0] = 999 and del[len(del)-2] = 998), the changes are reflected in all as well, since both slices share the same array.

This demonstrates that append in this case does not create a new array but modifies the existing one.

If you want to avoid this behavior and create an independent copy with the element removed, you should explicitly copy the data:

func deleteElementCopy(s []int, idx int) []int {
    result := make([]int, 0, len(s)-1)
    result = append(result, s[:idx]...)
    result = append(result, s[idx+1:]...)
    return result
}

Thus, changes in the new slice will not affect the original.

Conclusion: In your code, del and all share the underlying array, so changes in del are reflected in all. This is related to how slices and append work in Go.