doulin1867 2015-07-11 09:06
浏览 84
已采纳

将不同类型的参数传递给函数

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 =]

  • 写回答

2条回答 默认 最新

  • doushai4890 2015-07-11 09:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算