recursion - 覆盖变量时的递归
问题描述
我希望你能帮助我,因为这让我很头疼。
我正在为之后执行的中间件创建一个链。但它似乎已经变得反复出现。匿名函数中的变量next
指向自身。
type MiddlewareInterface interface {
// Run the middleware for the given request, and receive the next handler.
Run(http.ResponseWriter, *http.Request, http.Handler)
}
createChain(collection []MiddlewareInterface, handler http.Handler) http.Handler
next := handler
for _, middlew := range collection {
next = func(w http.ResponseWriter, res *http.Request) {
middlew.Run(w, res, next)
}
}
return next
}
我知道这是一个菜鸟问题,但我真诚地想了解是什么原因造成的,以及如何解决这个问题。期待您的回答!
解决方案
似乎这是循环问题中的闭包变量。您正在创建一个next
在每个循环中捕获的函数,但这意味着所有函数共享相同的变量next
,并且它们都将具有最后一个循环中留下的值。我认为您可以通过在循环范围内引入一个新的临时变量来修复它:
func createChain(collection []MiddlewareInterface, handler http.Handler) http.Handler
next := handler
for _, middlew := range collection {
thisNext:= next
mw := middlew
next = func(w http.ResponseWriter, res *http.Request) {
mw.Run(w, res, thisNext)
}
}
return next
}
可能新变量定义的位置不太正确,但闭包问题肯定是问题的根源。http 中间件处理程序通常不是如何工作的,因为它们通常相互包装而不是被链接。
推荐阅读
- python - 自动将散点图的标签放置在点周围,以免它们相互覆盖
- c# - 通过使用我的 Nuget 包的 VS2015 构建 .NET 项目不会复制 .config 文件
- docker - 重新启动在 Docker 容器中运行的应用程序会破坏堆栈网络
- java - 我想在 android 中生成四个不同的随机数,但它们的总数不应大于指定范围,如 0 到 69
- mysql - 我无法用 MYSQL 中的更新、设置、替换替换注册表中的部分名称
- c# - c#如何让用户选择文件夹然后输入
- r - 如何将“Bid.Price”添加到 R 上的向量中(使用 TrueFX 库)
- python - Python 3.7 中的基本计时器
- android - 意外标记(使用 ';' 分隔同一行上的表达式)
- c# - Angular + Core API:如何拦截请求响应错误正文