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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With