数组 – 如何在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中提到的那样
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |