Can functions be passed as parameters?

后端 未结 6 1055
北荒
北荒 2020-12-12 12:06

In Java I can do something like

derp(new Runnable { public void run () { /* run this sometime later */ } })

and \"run\" the code in the me

6条回答
  •  自闭症患者
    2020-12-12 12:13

    Here is the sample "Map" implementation in Go. Hope this helps!!

    func square(num int) int {
        return num * num
    }
    
    func mapper(f func(int) int, alist []int) []int {
        var a = make([]int, len(alist), len(alist))
        for index, val := range alist {
    
            a[index] = f(val)
        }
        return a
    }
    
    func main() {
        alist := []int{4, 5, 6, 7}
        result := mapper(square, alist)
        fmt.Println(result)
    
    }
    

提交回复
热议问题