Search code examples
gotypesslicego-interface

Remove an interface item from a slice


I want to remove an item in a slice w/o having to use a specific function for every type of items in the slice. So, I am using interface{} as the slice item type:

package main

import "fmt"

func sliceRemoveItem(slice []interface{}, s int) []interface{} {
  return append(slice[:s], slice[s+1:]...)
}

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

  fmt.Println(array)
  fmt.Println(sliceRemoveItem(array,1))
}

But goLang doesn't like it:

./prog.go:13:30: cannot use array (type []int) as type []interface {} in argument to sliceRemoveItem

https://play.golang.org/p/wUrR5iGRZ5Y

Any idea how to do this? Is it possible to use a generic single function accepting any type of slice items?

Refs: How to delete an element from a Slice in Golang


Solution

  • You're trying to pass a slice of int as a slice of interface{}. Go doesn't do this conversion implicitly since it is a costly operation.

    Check out this answer: https://stackoverflow.com/a/12754757

    You can either accept []interface{}, but do the conversion explicitly, or specify the type as []int. This works:

    package main
    
    import "fmt"
    
    func sliceRemoveItem(slice []int, s int) []int {
      return append(slice[:s], slice[s+1:]...)
    }
    
    func main() {
      array := []int{1,2,3,4,5,6,7}
    
      fmt.Println(array)
      fmt.Println(sliceRemoveItem(array,1))
    }