有趣的是,Rob
Pike刚刚提出了(18小时前)库过滤器,该过滤器可以满足您的要求:
例如查看Choose()
// Choose takes a slice of type []T and a function of type func(T) bool. (If// the input conditions are not satisfied, Choose panics.) It returns a newly// allocated slice containing only those elements of the input slice that// satisfy the function.
在这里测试:
func TestChoose(t *testing.T) { a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} expect := []int{2, 4, 6, 8} result := Choose(a, isEven)正如评论中[
twotwotwo]指出的那样,该库的GoDoc指出:
软件包
filter包含实用程序功能,用于通过过滤器功能的分布式应用程序来过滤切片。该软件包是一个实验,旨在了解在Go中编写此类代码有多么容易。这很容易,但是
for循环同样容易且效率更高。您不应该使用此软件包。
该警告反映在文档“
Go泛型讨论摘要 ”的“
功能代码 ”部分中:
这些是通常的高阶函数如
map,reduce(fold),filter,zip等等案例 :
类型安全的数据转换:map,fold,zip使用泛型的优点 :
表达数据转换的简洁方法。使用泛型的缺点 :
最快的解决方案需要考虑何时以及按什么顺序应用这些转换,以及每个步骤生成多少数据。
对于初学者来说很难阅读。替代解决方案 :
使用
for循环和常用语言构造。



