循环变量符号被函数字面量捕获

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

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)

	}
}

huangapple
  • 本文由 发表于 2021年7月23日 12:24:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/68494028.html
匿名

发表评论

匿名网友

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

确定