golang实现高阶函数之map
1 package main 2 3 import "fmt" 4 5 func iMap(num []int, f func(a int) int) []int{ 6 var r []int 7 8 for _, n := range num{ 9 r = append(r, f(n)) 10 } 11 12 return r 13 } 14 15 func main() { 16 num := []int{2, 4, 6, 8} 17 18 fmt.Println("before: ", num) 19 20 result := iMap(num, func(a int) int{ 21 return a * 2 22 }) 23 24 fmt.Println("after: ", result) 25 }
执行结果:
before: [2 4 6 8] after: [4 8 12 16]