HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Delete element in a slice

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
elementdeleteslice

Problem

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?

Solution

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 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:

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


is essentially:

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


Now, you may be wondering, why not just do

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


Well, the function definition of append is

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


So 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.

Code Snippets

a = append(a[:i], a[i+1:]...)
a = append(a[:0], a[1:]...)
a = append(a[:0], a[1], a[2])
a = append(a[1:]...)
func append(slice []Type, elems ...Type) []Type

Context

Stack Overflow Q#25025409, score: 292

Revisions (0)

No revisions yet.