GoLang 实现自定义类型的匿名函数

标签 go anonymous-function

我已经在 exercism.io 上完成了 strains 练习。我正在重构我的解决方案。对于上下文:Ints.Keep 接受一个谓词函数,并为谓词函数为真的每个元素返回一个经过过滤的 Ints 类型 slice 。相反地​​,Discard 返回谓词不为真的所有元素。 Discard 返回 Keep 的倒数。我是这样实现的:

func (i Ints) Keep(pred func(int) bool) (out Ints) {
    for _, elt := range i {
        if pred(elt) {
            out = append(out, elt)
        }
    }
    return
}

func (i Ints) Discard(f func(int) bool) Ints {
    return i.Keep(func(n int) bool { return !f(n) })
}

Example usage

现在我想稍微清理一下。我要创建:

type Predicate func(int) bool

然后我想在输入为 Predicate 的地方实现 Keep 和 Discard。当我尝试在 Discard 中创建匿名函数以返回 Keep 时遇到问题:

func (i Ints) Discard(p Predicate) Ints {
    return i.Keep(Predicate(n int) { return !p(n) })
}

这可能吗?我找不到创建命名 func 类型的匿名函数的方法。

最佳答案

您可以通过将匿名函数转换为 Predicate 来实现,如下所示:

func (i Ints) Discard(p Predicate) Ints {
    return i.Keep(Predicate(func(i int) bool { return !p(i) }))
}

这不是我想要的那么干净,但我打赌这是最好的。

关于GoLang 实现自定义类型的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961456/

相关文章:

performance - 为什么在 Go 中交换 []float64 的元素比在 Rust 中交换 Vec<f64> 的元素更快?

JavaScript 匿名函数数组到 Java 的翻译

php - Laravel 4 - 容器类 : share function & closure logic

rest - golang 中特定于平台的反序列化?

dictionary - 分配给 nil 映射中的条目

go - 如何测试一个端点?

javascript - 我如何使用自执行匿名函数中的对象?

go - 通过上下文取消进入异步/等待模式

c# - 委托(delegate)、Lambda、Action、Func、匿名函数

php - 为什么无法在 PHP 的匿名函数中从父/外部作用域访问变量?