function - 函数可以作为参数传递吗?

标签 function go

在 Java 中我可以做类似的事情

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

然后“运行”方法中的代码。处理起来很痛苦(匿名内部类),但可以做到。

Go 有什么东西可以促进函数/回调作为参数传入吗?

最佳答案

是的,请考虑以下一些示例:

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 "" })
}

播放:http://play.golang.org/p/XNMtrDUDS0

游览:https://tour.golang.org/moretypes/25 (函数闭包)

关于function - 函数可以作为参数传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655464/

相关文章:

c++ - 有关C++中函数的默认返回类型的查询

c++ - 优化for循环的函数调用

dictionary - 在 map 中存储值和 slice

javascript - JavaScript 中的所有函数本质上都是方法吗?

c++ - 引用函数 "int &foo();"是如何工作的?

go - 为什么我可以根据值直接测试接口(interface)?

arrays - Go中的初始化结构数组

unit-testing - 如何在不同的包中测试未导出的结构字段?

go - 在实例生成期间修改结构字段

php - 是否可以替换 (monkeypatch) PHP 函数?