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]

 

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