英文:
loop variable symbol captured by func literal
问题
为什么在 Go Playground 中会出现 loop variable symbol captured by func literal
的错误,但在编译过程中却没有出现?
package main
import (
"log"
)
func main() {
symbols := []string{"DOGEUSDT", "BTCUSDT", "ETHUSDT"}
for _, symbol := range symbols {
log.Print("aaa ", symbol)
// 为每个 symbol 创建一个 proc,以便我们可以处理重新连接。
go func() {
log.Print("bbb ", symbol)
}()
}
}
英文:
Why am I getting loop variable symbol captured by func literal
in the go playground but not during compilation?
package main
import (
"log"
)
func main() {
symbols := []string{"DOGEUSDT", "BTCUSDT", "ETHUSDT"}
for _, symbol := range symbols {
log.Print("aaa ", symbol)
// Create a proc for each symbol so we can handle reconnects.
go func() {
log.Print("bbb ", symbol)
}()
}
}
答案1
得分: 2
这只是go-vet发出的一个警告信息。这里的func literal
表示匿名函数。为了满足go-vet的要求,我们需要将循环变量
作为参数传递。
请查看下面重构后的代码。在playground上有一个可工作的示例链接。
package main
import (
"log"
)
func main() {
symbols := []string{"DOGEUSDT", "BTCUSDT", "ETHUSDT"}
for _, symbol := range symbols {
log.Print("aaa ", symbol)
// 为每个符号创建一个进程,以便我们可以处理重新连接。
go func(newSymbol string) {
log.Print("bbb ", newSymbol )
}(symbol)
}
}
英文:
This is just a warning message alerted by go-vet. func literal
means anonymous function here. To satisfy the go-vet we need to pass loop variable
as a parameter.
Check the refactored code below. Working example on playground here.
package main
import (
"log"
)
func main() {
symbols := []string{"DOGEUSDT", "BTCUSDT", "ETHUSDT"}
for _, symbol := range symbols {
log.Print("aaa ", symbol)
// Create a proc for each symbol so we can handle reconnects.
go func(newSymbol string) {
log.Print("bbb ", newSymbol )
}(symbol)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论