douyang2530 2016-07-22 11:57
浏览 86
已采纳

在Go中,如何使用切片创建通用函数?

Let's say I want to write a function that finds a value in a slice

I intuitively want to write:

func find(s []interface{}, f func(interface{})bool) int {
    for i, item := range s {
        if f(item) {
            return i
        }
    }
    return -1
}

however I don't manage to do this with Go. I could have an interface with

Len() int
Value(int) interface{}
...

and this would work but in my real code things are more complicated (I need to do slices[from:end] etc), append, ... etc and if I redefine all this in an interface I end up having a lot of code. Is there a better way?

  • 写回答

3条回答 默认 最新

  • doujiang5211 2016-07-22 12:16
    关注

    You can use reflection. I wrote this function for a project, feel free to use it:

    // InSlice returns true if value is in slice
    func InSlice(value, slice interface{}) bool {
        switch reflect.TypeOf(slice).Kind() {
        case reflect.Slice, reflect.Ptr:
            values := reflect.Indirect(reflect.ValueOf(slice))
            if values.Len() == 0 {
                return false
            }
    
            val := reflect.Indirect(reflect.ValueOf(value))
    
            if val.Kind() != values.Index(0).Kind() {
                return false
            }
    
            for i := 0; i < values.Len(); i++ {
                if reflect.DeepEqual(values.Index(i).Interface(), val.Interface()) {
                    return true
                }
            }
        }
        return false
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大