Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate an integer in for-range loop in Go 1.22?

Go 1.22 has been released today. According to the release note,

"For" loops may now range over integers. For example:

package main

import "fmt"

func main() {
    for i := range 10 {
        fmt.Println(10 - i)
    }
    fmt.Println("go1.22 has lift-off!")
}

See the spec for details.

I want to learn the details but it seems the spec doesn't explain about the syntax at all.

I added #language-lawyer tag as I want strict understandings.

like image 982
ynn Avatar asked Jan 17 '26 03:01

ynn


1 Answers

Today (2024/02/08), the spec has been updated to the latest version.

According to the spec, the only syntax allowed is this:

for i := range n {
    //...
}
  • n is a (possibly untyped) integer expression.

  • It iterates from 0 to n - 1. (n is exclusive.)

  • If n <= 0, the loop iterates nothing.

  • Only one loop variable can be specified. (for i, j := 10 is (naturally) invalid.)

  • Unlike in Python, you cannot specify a step or iterate in reverse order.


Example:

playground

package main

import "fmt"

func main() {
    for i := range 5 {
        fmt.Println(i) //=> 0 1 2 3 4
    }

    var i int
    for i = range 1 + 2 {
        fmt.Println(i) //=> 0 1 2
    }

    for i := range 0 {
        fmt.Println(i) //compiles but not executed
    }

    for i := range -1 {
        fmt.Println(i) //compiles but not executed
    }
}
like image 195
ynn Avatar answered Jan 19 '26 20:01

ynn