// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
我不知道如何使用此功能,任何帮助将不胜感激。
答案 0 :(得分:1)
https://play.golang.org/p/Asc4v08wDO
package main
import "fmt"
// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
func odd(i int) bool {
return i%2 != 0
}
func even(i int) bool {
return !odd(i)
}
func main() {
v := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Println(Filter(v, odd))
fmt.Println(Filter(v, even))
}