Home  >  Article  >  Backend Development  >  Why Do Anonymous Functions in Closures Print Only the Last Job\'s Description in For Loops?

Why Do Anonymous Functions in Closures Print Only the Last Job\'s Description in For Loops?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 18:09:13124browse

Why Do Anonymous Functions in Closures Print Only the Last Job's Description in For Loops?

Anonymous Functions in for Loops with Closures

When scheduling tasks using the cron library, a common error arises when iterating through a list of jobs and attempting to use anonymous functions within the loop. This error is particularly evident when each job should print its own unique description, but instead prints the description of the last job in the list.

The underlying issue lies in the way anonymous functions handle variables. When iterating through a list, the loop variable will take on the value of each element in the list sequentially. However, the anonymous functions within the loop are bound to the original loop variable, which is shared among all iterations. This means that all anonymous functions end up using the same value of the loop variable, resulting in the last job's description being printed multiple times.

To resolve this issue, it is necessary to create a new variable for each iteration of the loop, thus ensuring that each anonymous function has its own instance of the variable. This technique prevents the complications caused by closures.

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 adjustment, each job will have its own description, printed correctly when its scheduled time arrives.

The above is the detailed content of Why Do Anonymous Functions in Closures Print Only the Last Job\'s Description in For Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn