繁体   English   中英

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

[英]How to write func for the generic parameter in golang

我正在尝试编写一个函数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)

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

正如Rob Pike在这个帖子中提到的那样

是否可以在Go类型开关中表达“任何地图”,“任何数组”或“任何切片”?

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

您只能迭代特定类型的列表,例如具有已知函数的接口。
您可以看到一个示例“ 我们可以在go中编写通用阵列/片重复数据删除吗?

即使使用反射,也可以将切片作为interface{}传递, 如此线程所示 ,容易出错(参见本示例 )。

你对Map的定义有些不完整。 通常的方式来声明它会有mapper方法。 您的示例至少可以通过这种方式实现

package main

import "fmt"

// Interface to specify something thet can be mapped.
type Mapable interface {
}


func main() {
    list_1 := []int{1, 2, 3, 4}
    list_2 := []string{"a", "b", "c", "d"}
    Map(print, list_1)
    Map(print, list_2)
}
func print(value Mapable){
fmt.Print(value)
}

// This function maps the every element for
// all []types of array.
func Map(mapper func(Mapable), list ... Mapable) {
    for _, value := range list {
        mapper(value)
    }
}

有效 需要说它有点无关紧要。 因为不,Go在Hindley-Milner中并没有“仿制品”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM