我正在尝试创建一种类似于 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/