Anonymous Functions in for Loops: Unexpected Behavior
In your Go program, you've discovered that your scheduler is not printing the expected output for each scheduled job. The problem is attributed to the use of anonymous functions in the for loop.
In a for loop, the anonymous function captures the loop variable job each time the loop executes. However, since there is only one anonymous function, it uses the job variable from the last iteration of the loop. This results in all jobs printing the description of the last job.
Solution: Create a New Variable for Each Iteration
To resolve this issue, create a new variable for each iteration of the loop. This will ensure that each anonymous function captures its own unique value of the loop variable:
for _, job := range config.Jobs { realJob := job // a new variable each time through the loop c.AddFunc("@every "+realJob.Interval, func() { DistributeJob(realJob) }) log.Println("Job " + realJob.Name + " has been scheduled!") }
With this modification, each anonymous function will have its own copy of the job variable, correctly printing the description of the job it represents.
The above is the detailed content of Why Do Anonymous Functions in Go\'s `for` Loops Capture the Final Value of the Loop Variable?. For more information, please follow other related articles on the PHP Chinese website!