1. package main
  2. import "fmt"
  3. type Traverser func(ele interface{})
  4. type Student struct {
  5. Name string
  6. Age int
  7. Height int
  8. }
  9. //这个是传指针的
  10. func filterPoint(stu []*Student, f func(*Student) bool) (result []*Student) {
  11. for _, s := range stu {
  12. if f(s) {
  13. result = append(result, s) //result在返回时有定义了,所以就不用在函数体内再定义一次
  14. }
  15. }
  16. return result
  17. }
  18. //这个是传指针的
  19. func ageJudge(age int) func(*Student) bool {
  20. return func(s *Student) bool {
  21. return s.Age > age
  22. }
  23. }
  24. //这个是传值的
  25. func filter(stu []Student, f func(Student) bool) (result []Student) {
  26. for _, s := range stu {
  27. if f(s) {
  28. result = append(result, s) //result在返回时有定义了,所以就不用在函数体内再定义一次
  29. }
  30. }
  31. return result
  32. }
  33. //这个是传值的
  34. func age(age int) func(Student) bool {
  35. return func(s Student) bool {
  36. return s.Age > age
  37. }
  38. }
  39. func main() {
  40. studentsPoint := []*Student{
  41. &Student{"liang", 18, 165},
  42. &Student{"yuehan", 22, 166},
  43. }
  44. resultPoint := filterPoint(studentsPoint, ageJudge(20))
  45. fmt.Println(resultPoint) //这个返回的是结构秒的地址
  46. for _, s := range resultPoint {
  47. fmt.Println(*s)
  48. fmt.Println(s)
  49. }
  50. fmt.Println("-------------------")
  51. students := []Student{
  52. Student{"liang", 18, 165},
  53. Student{"yuehan", 22, 166},
  54. }
  55. result := filter(students, age(20)) //这个返回的是结构体
  56. fmt.Println(result)
  57. for _, s := range result {
  58. fmt.Println(s)
  59. }
  60. }

分类: web

标签:   golang