小编val*_*val的帖子

在Go中实现泛型函数的惯用方法

假设我想编写一个函数来检查谓词是否与切片中的元素匹配:

func IsIn(array []T, pred func(elt T) bool) bool {
    for _, obj := range array {
        if pred(obj) { return true;}
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

显然,以前的代码不会编译,因为T不存在.我可以用这样的代替它interface{}:

func IsIn(array[]interface{}, pred func(elt interface{}) bool) bool {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我很高兴让谓词执行转换:

IsIn([]interface{}{1,2,3,4}, func(o interface{}) {return o.(int) == 3; });
Run Code Online (Sandbox Code Playgroud)

但是,该函数将不接受任何类型的数组[]interface{}:

IsIn([]int{1,2,3,4}, func(o interface{}) { return o.(int) == 3; }) // DO NOT COMPILE
Run Code Online (Sandbox Code Playgroud)

同样地:

func IsIn(arr interface, pred func(o interface{}) bool) bool {
    for _, o := …
Run Code Online (Sandbox Code Playgroud)

generics reflection covariance go

5
推荐指数
1
解决办法
224
查看次数

标签 统计

covariance ×1

generics ×1

go ×1

reflection ×1