type ApplyFunc func(commitIndex uint64, cmd []byte) []byte
对于这个声明。我的理解是,这是一个函数指针。它的名字是 ApplyFunc。 并且此函数将 commitIndex 和 cmd 作为输入。它返回 []字节。
我的理解对吗? 谢谢!
最佳答案
Golang 函数是一流的,如本 go-example page 所示.
这是一个 named type ,这意味着您可以在需要 func(commitIndex uint64, cmd []byte) []byte
的任何地方使用 ApplyFunc
:请参阅“Golang: Why can I type alias functions and use them without casting?” .
意思是,正如Volker评论的那样,它不是函数或“指向函数的指针”。
它是一种类型,它允许您声明一个变量来存储任何函数,该函数遵循与其声明类型相同的函数签名,例如 function literal。 (或“匿名函数”)。
var af ApplyFunc = func(uint64,[]byte) []byte {return nil}
// (function literal or "anonymous function")
参见“Anonymous Functions and Closures”:您可以定义一个返回另一个函数的函数,利用闭包:
Function literals are closures: they may refer to variables defined in a surrounding function.
Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
(参见 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”所示,您可以在函数接收器 ApplyFunc
(!) 上定义函数。
关于前导 "type ***"的 golang 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25498505/