作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在尝试创建一种类似于 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/
我参加了一些类(class)并阅读了 YAGNI 的用途。但是,作为一个整体,这个原则从来没有让我满意。它引入了一个逻辑悖论。 作为一个假设,您正在设计一个打算向前扩展的框架。 YAGNI(可能还有
我是一名优秀的程序员,十分优秀!