在Golang中是否有像C++中的std::bind一样的方法来操作函数?

huangapple go评论111阅读模式
英文:

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++

huangapple
  • 本文由 发表于 2017年5月2日 11:17:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/43729511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定