gpt4 book ai didi

c++ - golang 中是否有一些方法像 C++ 中的 std::bind 那样操作函数?

转载 作者:IT王子 更新时间:2023-10-29 02:03:15 24 4
gpt4 key购买 nike

这是我的设计:

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) // where _1 hold the position for parameter `c *gin.Context`

像 std::bind 这样的函数

我如何在 Golang 中做到这一点?是否有一些更优雅的方法来完成这项工作?

最佳答案

关闭,这是我的解决方案:

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

然后 handler_new 可以用作:

handler_new(some_context)

这是一样的

handler_new = std::bind(PreExecute, _1, handler_old)

在 C++ 中

关于c++ - golang 中是否有一些方法像 C++ 中的 std::bind 那样操作函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com