在Go中,如何使用切片创建通用函数? [英] In Go, how can I make a generic function with slices?

查看:267
本文介绍了在Go中,如何使用切片创建通用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我直觉地想写:

  func find(s [] interface {},f func(interface {})bool)int {
for i,item:= range s {
如果f(物品){
返回i
}
}
返回-1
}

但是我无法用Go做到这一点。我可以有一个接口:

$ p $ lt; code> Len()int
Value(int)interface {}
。 ..

这可以工作,但在我真正的代码中事情更复杂(我需要做切片[from:end]等),append,...等等,如果我在界面中重新定义了所有这些,我就会得到很多代码。有没有更好的方法?

解决方案

您可以使用反射。我为一个项目编写了这个函数,可以随意使用它:

  //如果值在slice $ b中,InSlice返回true $ b func InSlice(value,slice interface {})bool {
switch reflect.TypeOf(slice).Kind(){
case reflect.Slice,reflect.Ptr:
values:= reflect.Indirect(reflect.ValueOf(slice))
如果values.Len()== 0 {
返回false
}

val:= reflect.Indirect (reflect.ValueOf(value))

如果val.Kind()!= values.Index(0).Kind(){
返回false
}

for i:= 0;我< values.Len(); i ++ {
if reflect.DeepEqual(values.Index(i).Interface(),val.Interface()){
return true
}
}
}
return false
}


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?

解决方案

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
}

这篇关于在Go中,如何使用切片创建通用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆