douyi1963 2012-09-29 18:45 采纳率: 0%
浏览 139
已采纳

可以在Go中将函数作为参数传递吗?

In Java I can do something like

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

and "run" the code in the method later. It's a pain to handle (anonymous inner class), but it can be done.

Does Go have something that can facilitate a function/callback being passed in as a parameter?

  • 写回答

6条回答 默认 最新

  • dqq3623 2012-09-29 19:18
    关注

    Yes, consider some of these examples:

    package main
    
    import "fmt"
    
    // convert types take an int and return a string value.
    type convert func(int) string
    
    // value implements convert, returning x as string.
    func value(x int) string {
        return fmt.Sprintf("%v", x)
    }
    
    // quote123 passes 123 to convert func and returns quoted string.
    func quote123(fn convert) string {
        return fmt.Sprintf("%q", fn(123))
    }
    
    func main() {
        var result string
    
        result = value(123)
        fmt.Println(result)
        // Output: 123
    
        result = quote123(value)
        fmt.Println(result)
        // Output: "123"
    
        result = quote123(func(x int) string { return fmt.Sprintf("%b", x) })
        fmt.Println(result)
        // Output: "1111011"
    
        foo := func(x int) string { return "foo" }
        result = quote123(foo)
        fmt.Println(result)
        // Output: "foo"
    
        _ = convert(foo) // confirm foo satisfies convert at runtime
    
        // fails due to argument type
        // _ = convert(func(x float64) string { return "" })
    }
    

    Play: http://play.golang.org/p/XNMtrDUDS0

    Tour: https://tour.golang.org/moretypes/25 (Function Closures)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教