0
votes

I just show the code, it is pretty simple, go play:

package main

import (
    "fmt"
)

func main() {
    a := []int{1,2,3,4,5,6}
    for i:=0 ; i < len(a); i++ {
        b := append(a[:i], a[i+1:]...)
        fmt.Println(b)
    }
    fmt.Println(a)
}

In the code above, I have a slice, and I wanted to delete it's element in a loop.

What I hope the output is:

23456
13456
12356
12346
12345

but I got:

[2 3 4 5 6]
[2 4 5 6 6]
[2 4 6 6 6]
[2 4 6 6 6]
[2 4 6 6 6]
[2 4 6 6 6]

why? the go's document say that if slice's capacity is not enough it will make a realloc for the element, and I even changed anything in origin slice...

can somebody explain me how this happen?

2
What you want can be done by using copy: play.golang.org/p/XPiDvJtRFe - abhink
b := append(a[:i], a[i+1:]...), sure, this code will change a - kien bui

2 Answers

0
votes

I think I know why.

the slice a[:i] will return a slice which's capacity size is 6(as the origin slice), so the append will not realloc a new slice but use the origin one.

0
votes
 b := append(a[:i], a[i+1:]...)

this code will change a Slice. My code:

func main() {
    a := []int{1, 2, 3, 4, 5, 6}
    for i := 0; i < len(a); i++ {
        a1 := make([]int,6)
        copy(a1, a)
        b := make([]int,5)
        b = a1[:i]
        b = append(b, a1[i+1:]...)
        fmt.Println(b)
    }
    fmt.Println(a)
}