Can functions be passed as parameters?

后端 未结 6 1066
北荒
北荒 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条回答
  •  Happy的楠姐
    2020-12-12 12:19

    You can pass function as parameter to a Go function. Here is an example of passing function as parameter to another Go function:

    package main
    
    import "fmt"
    
    type fn func(int) 
    
    func myfn1(i int) {
        fmt.Printf("\ni is %v", i)
    }
    func myfn2(i int) {
        fmt.Printf("\ni is %v", i)
    }
    func test(f fn, val int) {
        f(val)
    }
    func main() {
        test(myfn1, 123)
        test(myfn2, 321)
    }
    

    You can try this out at: https://play.golang.org/p/9mAOUWGp0k

提交回复
热议问题