加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

数组 – 如何在golang中为泛型参数编写func

发布时间:2020-12-16 19:26:19 所属栏目:大数据 来源:网络整理
导读:我正在尝试编写一个函数Map,以便它可以处理所有类型的数组. // Interface to specify generic type of array.type Iterable interface {}func main() { list_1 := []int{1,2,3,4} list_2 := []uint8{'a','b','c','d'} Map(list_1) Map(list_2)}// This funct
我正在尝试编写一个函数Map,以便它可以处理所有类型的数组.
// Interface to specify generic type of array.
type Iterable interface {
}

func main() {
    list_1 := []int{1,2,3,4}
    list_2 := []uint8{'a','b','c','d'}
    Map(list_1)
    Map(list_2)
}

// This function prints the every element for
// all []types of array.
func Map(list Iterable) {
    for _,value := range list {
        fmt.Print(value)
    }
}

但它会抛出编译时错误.

19: cannot range over list (type Iterable)

错误是正确的,因为范围需要数组,指向数组的指针,切片,字符串,映射或允许接收操作的通道,此处类型是Iterable.我认为我面临的问题是,将参数类型Iterable转换为数组类型.请建议,我怎么能用我的函数来处理泛型数组.

正如Rob Pike在 this thread中提到的那样

Is it possible to express “any map”,“any array” or “any slice” in a Go type switch?


不可以.静态类型必须准确.
空接口实际上是一种类型,而不是通配符.

您只能迭代特定类型的列表,例如具有已知函数的接口.
你可以看一个“Can we write a generic array/slice deduplication in go?”的例子

即使使用反射,传递切片作为接口{}也将如this thread shows所示,容易出错(见this example).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读