4

I was having some issues with Golang slices.

I understand that a slice is a pointer to an underlying array, but some of the behaviour feels a little odd.

I was trying to remove an item from a slice I managed to do it by copying the slice is there a better way?

In the code below the original slice is changed.

package main

import (
    "fmt"
)

func main() {
    mySlice := []int{1,2,3,4,5,6}
    pos := 3

    slicePart1 := mySlice[:pos+1]
    slicePart2 := mySlice[pos+2:]

    fmt.Println(mySlice)
    fmt.Println(slicePart1)
    fmt.Println(slicePart2)
    new := append(slicePart1,slicePart2...)
    fmt.Println(new)
    fmt.Println(mySlice)
}
peterSO
  • 158,998
  • 31
  • 281
  • 276
Charles Bryant
  • 995
  • 2
  • 18
  • 30

1 Answers1

6

For example,

package main

import "fmt"

func main() {
    s := []int{1, 2, 3, 4, 5, 6}
    fmt.Println(s)
    i := 3
    fmt.Println(i)
    s = append(s[:i], s[i+1:]...)
    fmt.Println(s)
}

Playground: https://play.golang.org/p/SVQEUE7Rrei

Output:

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

Or, if order is not important,

package main

import "fmt"

func main() {
    s := []int{1, 2, 3, 4, 5, 6}
    fmt.Println(s)
    i := 3
    fmt.Println(i)
    s[i] = s[len(s)-1]
    s = s[:len(s)-1]
    fmt.Println(s)
}

Playground: https://play.golang.org/p/lVgKew3ZJNF

Output:

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

For several other ways, see SliceTricks.

peterSO
  • 158,998
  • 31
  • 281
  • 276