golang实现高阶函数之filter

 1 package main
 2 
 3 import "fmt"
 4 
 5 type student struct{
 6     name string
 7     grade int8
 8 }
 9 
10 func filter(stu []student, f func(s student) bool) []student{
11     var r []student
12 
13     for _, s := range stu {
14         if f(s) == true {
15             r = append(r, s)
16         }
17     }
18 
19     return r
20 }
21 
22 func main() {
23     s1 := student{
24         "zhangsan",
25         90,
26     }
27 
28     s2 := student{
29         "lisi",
30         80,
31     }
32 
33     s3 := student{
34         "wanggang",
35         70,
36     }
37 
38     s := []student{s1, s2, s3}
39 
40     fmt.Println("all student: ", s)
41 
42     var result []student
43 
44     result = filter(s, func(s student) bool {
45         if s.grade < 90 {
46             return true
47         }
48         return false
49     })
50 
51     fmt.Println("less than 90: ", result)
52 }

 运行结果:

 

all student:  [{zhangsan 90} {lisi 80} {wanggang 70}]
less than 90:  [{lisi 80} {wanggang 70}]

 

posted @ 2019-06-20 10:56  蓝色天马  阅读(2483)  评论(0编辑  收藏  举报