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 does this delete trick with the append function work?
It would seem that it's grabbing everything before the first element (empty array)
Then appending everything after the first element (position zero)
What does the ... (dot dot dot) do?
There are two options:
A: You care about retaining array order:
B: You don't care about retaining order (this is probably faster):
See the link to see implications re memory leaks if your array is of pointers.
https://github.com/golang/go/wiki/SliceTricks
Rather than thinking of the indices in the
[a:]
-,[:b]
- and[a:b]
-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed0
before the element indexed as0
.Looking at just the blue numbers, it's much easier to see what is going on:
[0:3]
encloses everything,[3:3]
is empty and[1:2]
would yield{"B"}
. Then[a:]
is just the short version of[a:len(arrayOrSlice)]
,[:b]
the short version of[0:b]
and[:]
the short version of[0:len(arrayOrSlice)]
. The latter is commonly used to turn an array into a slice when needed.... is syntax for variadic arguments.
I think it is implemented by the complier using slice (
[]Type)
, just like the function append :when you use "elems" in "append", actually it is a slice([]type). So "
a = append(a[:0], a[1:]...)
" means "a = append(a[0:0], a[1:])
"a[0:0]
is a slice which has nothinga[1:]
is "Hello2 Hello3"This is how it works
Or since you're trying to find the index of the element that's to be deleted anyway,
Ok never mind. Right answer for the topic, but wrong answer for the question body.
In golang's wiki it show some tricks for slice, including delete an element from slice.
Link: enter link description here
For example a is the slice which you want to delete the number i element.
OR
Where
a
is the slice, andi
is the index of the element you want to delete:...
is syntax for variadic arguments in Go.Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example,
fmt.Println
can take as many arguments as you want).Now, when calling a function,
...
does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.So what this line does:
is essentially:
Now, you may be wondering, why not just do
Well, the function definition of
append
isSo the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.