Alessandro Resta
Alessandro Resta

Reputation: 1172

Passing different type's parameters to the function

I have this function and i would like to make it be able to receive all types of slices, not only []string, but []int and so on... I would like to know if is there some way to abstract the type when passing the parameter to the function header or if i should do other thing to accomplish that.

package removeDuplicate

// RemoveDuplicate remove duplicate items from slice setting it to arr2
func RemoveDuplicate(arr []string) []string {
    arr2 := arr[:1]
Loop:
    for i := 1; i < len(arr); {
        for j := 0; j < len(arr2); {
            if arr[i] != arr[j] {
                j++
            } else {
                i++
                continue Loop
            }
        }
        arr2 = append(arr2, arr[i])
        i++
    }
    return arr2
}

Thanks in advance =]

Upvotes: 2

Views: 75

Answers (2)

Ainar-G
Ainar-G

Reputation: 36199

Any kind of generic algorithms in Go can be implemented with either of two mechanisms: interfaces and reflection. With interfaces, you can do it similarly to the sort package:

type Slice interface {
    Len() int
    Swap(i, j int)
    Eq(i, j int) bool
    SubSlice(i, j int) Slice
}

func RemoveDuplicate(s Slice) Slice {
    n := 1
Loop:
    for i := 1; i < s.Len(); i++ {
        for j := 0; j < n; j++ {
            if s.Eq(i, j) {
                continue Loop
            }
        }
        s.Swap(n, i)
        n++
    }
    return s.SubSlice(0, n)
}

Playground with ints and strings: http://play.golang.org/p/WwC27eP72n.

Upvotes: 0

Dmitri Goldring
Dmitri Goldring

Reputation: 4363

If you alter the function signature to accept interface{} you can get something that works on built in types.

package main

import "fmt"

func main() {
    x := []interface{}{"bob", "doug", "bob"}
    fmt.Println(RemoveDuplicate(x))
    y := []interface{}{1, 3, 1}
    fmt.Println(RemoveDuplicate(y))
    z := []interface{}{"bob", "2", "doug", 3, 2, "bob"}
    fmt.Println(RemoveDuplicate(z)) 
}

func RemoveDuplicate(arr []interface{}) []interface{} {
    arr2 := arr[:1]
Loop:
    for i := 1; i < len(arr); {
        for j := 0; j < len(arr2); {
            if arr[i] != arr[j] {
                j++
            } else {
                i++
                continue Loop
            }
        }
        arr2 = append(arr2, arr[i])
        i++
    }
    return arr2
}

Have a look at the FAQ Can I convert a []T to an []interface{}? (and the one before) for more information.

Upvotes: 2

Related Questions