英文:
Are there some methods in golang manipulate function like std::bind in C++?
问题
这是我的设计:
type Handler func(c *gin.Context)
func PreExecute(c *gin.Context, handle_func Handler) Handler {
if c.User.IsAuthorized {
return handle_func
} else {
return some_error_handle_func
}
}
我想要像Python中的装饰器一样,通过PreExecute修饰每个处理程序。所以我在golang中寻找一些类似std::bind的函数,以便使PreExecute的签名与Handler完全相同。
我期望的是:
handler = std::bind(PreExecute, _1, handler) // _1代表参数`c *gin.Context`的位置
类似std::bind的函数
在Golang中,我该如何做到这一点?是否有更优雅的方法来实现这个功能?
英文:
Here is my design:
type Handler func(c *gin.Context)
func PreExecute(c *gin.Context, handle_func Handler) Handler {
if c.User.IsAuthorized {
return handle_func
} else {
return some_error_handle_func
}
}
and I want to decorate every handler by PreExecute just like the decoration in Python. So I am looking for some std::bind functions in golang to get PreExecute a exactly same signature as Handler
What I expect:
handler = std::bind(PreExecute, _1, handler) // where _1 hold the position for parameter `c *gin.Context`
some function like std::bind
How can I do that in Golang? Are there some more elegant methods to get this work?
答案1
得分: 2
闭包,这是我的解决方案:
handler_new := func(c *gin.Context) { return PreExecute(c, handler_old)(c) }
然后可以使用 handler_new
:
handler_new(some_context)
这与 C++ 中的 std::bind(PreExecute, _1, handler_old)
相同。
英文:
Closure, here is my solution:
handler_new = func(c *gin.Context){ return PreExecute(c, handler_old)(c) } // since there is no return value of handler, so just do not use `return` statements, I will not correct this error
and then handler_new can be used as:
handler_new(some_context)
It's the same as
handler_new = std::bind(PreExecute, _1, handler_old)
in C++
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论