go - 在 go 中使用回调和函数作为类型

标签 go

我正在尝试创建一种类似于 Go 中的 Express (NodeJS) 路由方法的函数:

app.get("route/here/", func(req, res){
    res.DoStuff()
});    

在此示例中,我希望“foo”(类型)与上述方法中的匿名函数相同。这是我使用 Go 的失败尝试之一:

type foo func(string, string)

func bar(route string, io foo) {
        log.Printf("I am inside of bar")
        // run io, maybe io() or io(param, param)?
}

func main() {
        bar("Hello", func(arg1, arg2) {
                return  arg + arg2
        })
}

我该如何解决我的困境?我不应该使用类型而使用其他类型吗?我有哪些选择?

最佳答案

您走在正确的轨道上 - 在您正在使用的上下文中为函数创建类型可以增加更清晰的设计意图和额外的类型安全性。

你只需要稍微修改一下你的例子就可以编译了:

package main

import "log"

//the return type of the func is part of its overall type definition - specify string as it's return type to comply with example you have above
type foo func(string, string) string

func bar(route string, io foo) {

    log.Printf("I am inside of bar")
    response := io("param", "param")
    log.Println(response)

}

func main() {

    bar("Hello", func(arg1, arg2 string) string {
        return arg1 + arg2
    })

}

关于go - 在 go 中使用回调和函数作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39843134/

相关文章:

go - 在 Go 中解密非 ASCII 装甲 PGP 文件

go - 无法在 GoLand 中运行测试功能 : cannot find package "."

go - 我不能改变这个结构我也不明白为什么

mongodb 聚合在 golang 中给出错误

templates - 如何使用 Go 模板在单个语句中使用多个参数

templates - 在 golang gin 简单模板示例中,如何呈现不带引号的字符串?

go - 参数是接口(interface)列表{}

go - 如何从Goroutines中捕获错误?

go - "go test"报告不正确的语句覆盖率

mongodb - 如何在golang中连接mongodb 3.0