具有领先“类型***”的golang功能

时间:2014-08-26 05:14:47

标签: go

type ApplyFunc func(commitIndex uint64, cmd []byte) []byte

对于此声明。我的理解是,这是一个函数指针。它的名字是ApplyFunc。 此函数将commitIndex和cmd作为输入。它返回[] byte。

我的理解是对的吗? 谢谢!

1 个答案:

答案 0 :(得分:6)

Golang函数是一流的,如go-example page所示。

这是 named type ,这意味着您可以在ApplyFunc所需的任何地方使用func(commitIndex uint64, cmd []byte) []byte:请参阅“Golang: Why can I type alias functions and use them without casting?”。< / p>

这意味着,正如Volker所评论的那样,它不是函数或“指向函数的指针”。
它是一个类型,它允许您声明一个存储任何与其声明类型相同的func签名的函数的变量,如function literal(或“匿名函数”)。

var af ApplyFunc = func(uint64,[]byte) []byte {return nil}
                 // (function literal or "anonymous function")

参见“Anonymous Functions and Closures”:您可以定义一个函数,它返回另一个函数,利用闭包:

  

函数文字是闭包:它们可以引用周围函数中定义的变量   然后,这些变量在周围函数和函数文本之间共享,只要它们可访问,它们就会存在。

(见playground example

type inc func(digit int) int

func getIncbynFunction(n int) inc {
    return func(value int) int {
        return value + n
    }
}

func main() {
    g := getIncbynFunction
    h := g(4)
    i := g(6)
    fmt.Println(h(5)) // return 5+4, since n has been set to 4
    fmt.Println(i(1)) // return 1+6, since n has been set to 6
}

另外,如“Golang function pointer as a part of a struct”所示,您可以在func接收器ApplyFunc(!)上定义函数。