具有领先"类型***"的golang功能

Buf*_*lls 2 go

type ApplyFunc func(commitIndex uint64, cmd []byte) []byte
Run Code Online (Sandbox Code Playgroud)

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

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

Von*_*onC 6

Golang函数是一流的,如此示例页面所示.

它是一个命名类型,这意味着你可以ApplyFunc在任何需要的地方使用func(commitIndex uint64, cmd []byte) []byte:参见" Golang:为什么我可以输入别名函数并在不进行转换的情况下使用它们? ".

这意味着,正如Volker所评论的那样,它不是一个函数或"函数指针".
它是一种类型,允许您声明一个变量,该变量存储任何与其声明类型相同的func签名的函数,如函数文字(或"匿名函数").

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

请参阅" 匿名函数和闭包 ":您可以定义一个函数,该函数返回另一个函数,利用闭包:

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

(见游乐场示例)

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
}
Run Code Online (Sandbox Code Playgroud)

另外,如" Golang函数指针作为结构的一部分 "所示,您可以在func接收器ApplyFunc(!)上定义函数.