索引超出范围goroutine golang

索引超出范围goroutine golang,go,goroutine,Go,Goroutine,索引超出范围错误,这在for循环生成的goroutine中似乎是不可能的 这是我正在执行的go代码。 问题是在goroutine中countlinks调用的参数之一的求值中产生了索引超出范围的错误。我们迭代的切片长度始终为2。根据我对go中for循环的理解,i不应该计算为2(在表达式grph.entryPoints[i]中产生超出范围的索引),但它确实是。请告诉我我有多疯狂 func main() { grph := structures.ConfigGraphDefault()

索引超出范围错误,这在for循环生成的goroutine中似乎是不可能的

这是我正在执行的go代码。 问题是在goroutine中countlinks调用的参数之一的求值中产生了索引超出范围的错误。我们迭代的切片长度始终为2。根据我对go中for循环的理解,
i
不应该计算为2(在表达式
grph.entryPoints[i]
中产生超出范围的索引),但它确实是。请告诉我我有多疯狂

func main() {
    grph := structures.ConfigGraphDefault()
    counter := structures.NewCounter()
    queue := structures.NewQueue()
    tracker := structures.NewTracker()
    fmt.Printf("entries: %v\nnodes: %v\n", grph.EntryPoints, grph.Nodes)
    wg := sync.WaitGroup{}
    fmt.Println(len(grph.EntryPoints))
    // this will always evaluate to 2
    l := len(grph.EntryPoints)
    for i := 0; i < l; i++ {
        wg.Add(1)
        go func() {
            fmt.Printf("index: %v, length of slice: %v\n", i, len(grph.EntryPoints))
            structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
            wg.Done()
        }()
    }
    wg.Wait()
    fmt.Printf("counter: %v", counter.GetCounts())
}
func main(){
grph:=structures.ConfigGraphDefault()
计数器:=结构。NewCounter()
队列:=结构。NewQueue()
跟踪器:=structures.NewTracker()
fmt.Printf(“条目:%v\n节点:%v\n”,grph.EntryPoints,grph.Nodes)
wg:=sync.WaitGroup{}
fmt.Println(透镜(grph.EntryPoints))
//这将始终计算为2
l:=长度(grph入口点)
对于i:=0;i
i
确实变为2,但仅在循环的最末端。但是,由于goroutine函数关闭在
i
上,因此它在goroutine启动时看不到
i
的值,而是在执行时看到
i
的值。换句话说,您的所有goroutine共享相同的变量
i

要解决这个问题,一种方法是将
i
复制到循环体内部声明的helper变量。更好的方法是将其作为参数传递给goroutine:

    go func(i int) {
        fmt.Printf("index: %v, length of slice: %v\n", i, len(grph.EntryPoints))
        structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
        wg.Done()
    }(i)