Cannot assign variable to anonymous func in for loop

后端 未结 1 1742
臣服心动
臣服心动 2021-01-21 06:57

I\'m studying go-lang by developing a task schedular. The cron library I use accepts a cron expression and a func as parameters to add a scheduler.

c.AddFunc(\"0 30 *         


        
相关标签:
1条回答
  • 2021-01-21 07:21

    While you are not using goroutines, the mistake you are making is almost identical to the one described here: https://github.com/golang/go/wiki/CommonMistakes#using-closures-with-goroutines

    To quote:

    The val variable in the above loop is actually a single variable that takes on the value of each slice element. Because the closures are all only bound to that one variable, there is a very good chance that when you run this code you will see the last element printed for every iteration instead of each value in sequence, because the goroutines will probably not begin executing until after the loop.

    So your attempted fix (to pass it as a parameter to your function) would in principle fix the problem, however you cannot pass a function with parameters to the cron library - a function with parameters is a different type from one without (in addition to which by adding the () you are actually calling the function in advance and trying to pass its return value).

    The simplest fix is to create a new variable for every iteration of the loop and avoid the whole problem, like so:

    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!")
    }
    
    0 讨论(0)
提交回复
热议问题