Index out of range error where it seems impossible in goroutine generated by for loop
This is the go code I am executing.
The problem is that an index out of range error is yielded inside the evaluation of one of the arguments to countlinks call in a goroutine. The length of the slice we're iterating against is ALWAYS 2. Based on my understanding of for loops in go, i
should never evaluate to 2 (yielding index out of range in expression grph.entryPoints[i]
), and yet it is. Please, tell me how I am crazy.
func main() {
grph := structures.ConfigGraphDefault()
counter := structures.NewCounter()
queue := structures.NewQueue()
tracker := structures.NewTracker()
fmt.Printf("entries: %v
nodes: %v
", 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
", i, len(grph.EntryPoints))
structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
wg.Done()
}()
}
wg.Wait()
fmt.Printf("counter: %v", counter.GetCounts())
}