github.com/kaydxh/golang@v0.0.131/tutorial/programming_paradigm/map.reduce_test.go (about) 1 package tutorial 2 3 import ( 4 "fmt" 5 "testing" 6 ) 7 8 type Employee struct { 9 Name string 10 Age int 11 Vacation int 12 Salary int 13 } 14 15 var list = []Employee{ 16 {"Hao", 44, 0, 8000}, 17 {"Bob", 34, 10, 5000}, 18 {"Alice", 23, 5, 9000}, 19 {"Jack", 26, 0, 4000}, 20 {"Tom", 48, 9, 7500}, 21 {"Marry", 29, 0, 6000}, 22 {"Mike", 32, 8, 4000}, 23 } 24 25 // 控制逻辑通过传递函数方式与业务逻辑分开 26 func EmployeeCountIf(list []Employee, fn func(e *Employee) bool) int { 27 count := 0 28 for i, _ := range list { 29 if fn(&list[i]) { 30 count += 1 31 } 32 } 33 return count 34 } 35 36 func EmployeeFilterIn(list []Employee, fn func(e *Employee) bool) []Employee { 37 var newList []Employee 38 for i, _ := range list { 39 if fn(&list[i]) { 40 newList = append(newList, list[i]) 41 } 42 } 43 return newList 44 } 45 46 func EmployeeSumIf(list []Employee, fn func(e *Employee) int) int { 47 var sum = 0 48 for i, _ := range list { 49 sum += fn(&list[i]) 50 } 51 return sum 52 } 53 54 func TestEmployeeCountIf(t *testing.T) { 55 testCases := []struct { 56 Age int 57 Salary int 58 }{ 59 { 60 Age: 40, 61 Salary: 6000, 62 }, 63 } 64 65 for i, testCase := range testCases { 66 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { 67 count := EmployeeCountIf(list, func(e *Employee) bool { 68 return e.Age > testCase.Age 69 }) 70 t.Logf("the number of age > %v is %v", testCase.Age, count) 71 count = EmployeeCountIf(list, func(e *Employee) bool { 72 return e.Salary > testCase.Salary 73 }) 74 t.Logf("the number of salary > %v is %v", testCase.Salary, count) 75 }) 76 } 77 }