前导 "type ***"的 golang 函数

标签 go

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/

相关文章:

go - 如何只构建,不运行

go - 添加一个从未调用过的函数可以改善行为?

go - 我如何确保我的消费者按顺序处理 kafka 主题中的消息,并且只处理一次?

go - vim-go、模块和 GoRename

go - 如何将方法用作 goroutine 函数

firebase - 使用 Firebase 进行通知,获取 `app instance has been unregistered`

go - 格式错误的模块路径...第一个路径元素中缺少点

go - 调用 ExecuteTemplate 收到 i/o 超时错误

logging - 为什么不在日志包中使用lock同步

postgresql - 如何安全地丢弃 golang 数据库/sql 池连接,例如当它们指向只读副本时?