SoFunction
Updated on 2025-03-05

Detailed explanation of two important updates to the Go 1.22 for loop

Go 1.22Version on2024Year2moon6Release on Sunday, introducing several important features and improvements. On the language level, this versionforThe loop has two updates:

  • Each iteration of the loop creates new variables
  • Loop supports iterating on integer ranges

This article will be correctforTwo updates of the loop are introduced.

Ready? Prepare a cup of your favorite coffee or tea and find out with this article.

Each iteration of the loop creates new variables

existGo 1.22Before the version,forThe variable declared by the loop is created only once and updated in each iteration. existGo 1.22In this, each iteration of the loop creates new variables, which will prevent unexpected sharing errors.

By the same code examples in differentGoRunning in the version, we can clearly see the difference between the running results, and thus feel the specific impact of language updates.

  • Go 1.21Version of the code example

package main

import "fmt"

func main() {
        done := make(chan bool)

        values := []string{"chen", "ming", "yong"}
        for _, v := range values {
                go func() {
                        (v)
                        done <- true
                }()
        }

        // Wait until all goroutines are executed        for _ = range values {
                <-done
        }
}

The code run results are as follows:

yong
yong
yong

  • existforAnonymous functions and loop variables in a loop bodyvA closure is formed. Closure capturedvReference (or address) of this causes all closure instances to be accessedvIn fact, the same memory address is accessed. becausevCreated only once and will be updated with each iteration. Therefore, the final print results are the same valueyong

  • Go 1.22Version code example

package main

import "fmt"

func main() {
        done := make(chan bool)

        values := []string{"chen", "ming", "yong"}
        for _, v := range values {
                go func() {
                        (v)
                        done <- true
                }()
        }

        // Wait until all goroutines are executed        for _ = range values {
                <-done
        }
}

The code run results are as follows:

yong
ming
chen

  • existGo 1.22In, each iteration of the loop creates a new variablev, which means that each closure holds a different onevReferences to variables, so the final print results will vary.

    Each iteration of the loop creates new variablesThis update effectively avoids common closure traps in previous versions and improves the security and predictability of the code.

Loop supports iterating on integer ranges

existGo 1.22Before the version, when we usefor rangeWhen only supportedarray or slicestringmapandchannelThe expression of type is iterated, andGo 1.22Starting from the version, additional new pairsintergerSupport for types, which means we can use integers directly for loop iteration.

package main

import "fmt"

func main() {
	for i := range 10 {
		(i)
	}
}

For integer values10, iterate the value from0arrive9Generate in incremental order. ifrangeThe following expression is0, then the loop does not perform any iteration.

summary

This article introducesGo 1.22VersionforTwo important updates made by the loop:Each iteration of the loop creates new variablesandLoop supports iterating on integer ranges

Each iteration of the loop creates new variables, effectively avoids common closure traps in previous versions, and improves the security and predictability of the code.

Loop supports iterating on integer ranges, greatly enhancedforThe flexibility of loops makes writing count loops more direct and concise.

This is the end of this article about the two important updates of Go 1.22 for loop. For more relevant content on Go 1.22 for loop updates, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!