如何实现通用筛选器函数?

假设我正在实现这个函数来过滤Golang中的切片:


 func Filter(filter func(n int) bool) func(list []int) []int {

   return func(list []int) []int {

     r := make([]int, 0)

     for _, n := range list {

         if filter(n) {

             r = append(r, n)

         }

   }


     return r

 } 

}

要这样使用:


list := []int{1, 4, 3, 2, 7, 4, 9, 7}

r := Filter(func(n int) bool { return n > 3 })(list)


fmt.Println(r)

这工作正常,但我有以下问题:

  1. 我是否应该使用完整的 func 语法而不是 lambda 样式表达式?

  2. 如果我希望筛选器筛选任何类型的切片,我应该使用哪种返回类型?

谢谢!


沧海一幻觉
浏览 88回答 1
1回答

FFIVE

据我所知,还没有关于更简洁的匿名函数表示法(“lambda”)的提议被接受。随着Go 1.18的发布,计划在2022年初向该语言添加类型参数(又名泛型)。然后,您将能够编写下面的程序(playground)。如果您可以等到那时,请这样做。无论如何,通常不鼓励使用反射包并使用空接口{}和类型断言来填充代码。在Go 1.18之前,一个可行的替代方案是使用go generate来生成您需要的不同专业化(用于,等)。intstringpackage mainimport "fmt"func Filter[T any](filter func(n T) bool) func(T []T) []T {&nbsp; &nbsp; return func(list []T) []T {&nbsp; &nbsp; &nbsp; &nbsp; r := make([]T, 0, len(list))&nbsp; &nbsp; &nbsp; &nbsp; for _, n := range list {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if filter(n) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r = append(r, n)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return r&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; list := []int{1, 4, 3, 2, 7, 4, 9, 7}&nbsp; &nbsp; r := Filter(func(n int) bool { return n > 3 })(list)&nbsp; &nbsp; fmt.Println(r)&nbsp; &nbsp; list2 := []string{"foo", "bar", "baz", "qux", "quux"}&nbsp; &nbsp; r2 := Filter(func(s string) bool { return len(s) <= 3 })(list2)&nbsp; &nbsp; fmt.Println(r2)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go