Delete item in slice

func main() { a := []string{"Hello1", "Hello2", "Hello3"} fmt.Println(a) // [Hello1 Hello2 Hello3] a = append(a[:0], a[1:]...) fmt.Println(a) // [Hello2 Hello3] } 

How to remove the trick using the add function?

It would seem that it captures everything up to the first element (empty array)

Then add everything after the first element (zero position)

What does ... (dot dot)?

+67
go
Jul 29 '14 at 21:36
source share
4 answers

Where a is the slice, and i is the index of the element you want to delete:

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

... is the syntax for variational arguments in Go.

Basically, when you define a function, it puts all the arguments that you pass into one fragment of this type. By doing this, you can pass as many arguments as you want (for example, fmt.Println can take as many arguments as you want).

Now, when the function is called , ... does the opposite: it unpacks the slice and passes them as separate arguments to the variable function.

So what this line does:

 a = append(a[:0], a[1:]...) 

essentially:

 a = append(a[:0], a[1], a[2]) 

Now you may be wondering why not just do

 a = append(a[:1]...) 

Well, append function definition is equal

 func append(slice []Type, elems ...Type) []Type 

So, the first argument should be a slice of the correct type, the second argument should be a variable, so we pass an empty fragment, and then unpack the rest of the slice to fill in the arguments.

+129
Jul 29 '14 at 21:47
source share

There are two options:

A: You care about maintaining the order of the array:

 a = append(a[:i], a[i+1:]...) // or a = a[:i+copy(a[i:], a[i+1:])] 

B: You don't care about maintaining order (this is probably faster):

 a[i] = a[len(a)-1] // Replace it with the last one. a = a[:len(a)-1] // Chop off the last one. 

See the link to see the effects of memory leaks if your array has pointers.

https://github.com/golang/go/wiki/SliceTricks

+18
May 21 '16 at 6:30 a.m.
source share

... is the syntax for variational arguments.

I think this is implemented by complier using slice ( []Type) , like the append function:

 func append(slice []Type, elems ...Type) []Type 

when you use "elems" in the "append", it is actually a slice ([]) type. So, " a = append(a[:0], a[1:]...) " means " a = append(a[0:0], a[1:]) "

a[0:0] is a slice that has nothing

a[1:] is "Hello2 Hello3"

Here is how it works

+5
Jul 30 '14 at 2:52
source share

Or, since you are trying to find the index of the item to be deleted anyway,

 // na = new a, da = a that to be deleted var na []string for _, v := range a { if v == da { continue } else { na = append(na, v) } } a = na 

Good, never mind. The correct answer to this topic, but the wrong answer to the question.

+1
May 01 '17 at 10:44 p.m.
source share



All Articles