For range with ints


chatgpt is saying that for range with integer works different, like it is converted to an iterable type first, (to string) and iterates over rune ‘5’ only once, but when I run it in playground, it is working like I would have written:
for i := 0; i < count; i++ {
fmt.Println(“Hello!”)
}

Is this a new feature added in recent go update mine is running in go1.23.1 darwin/arm64.
Is this secure to use?

2 Likes

Interesting example indeed as I am learning too.

package main

import (
	"fmt"

)

func main() {
	count:=5
	for range count{
	fmt.Println("count", count)
	}
}

Outputs:
count 5
count 5
count 5
count 5
count 5

Below example is like in Python, would be worth to add your one to official GO “A Tour by GO” and to GO by example website with explanation.

https://gobyexample.com/for

for i := range 3 {
        fmt.Println("range", i)
    }

it will print:
range 0
range 1
range 2

Python code equivalent

for i in range (3):
     print("range", i)

range 0
range 1
range 2

In Go, range is design for iterate over collection , here 3 & 5 is single integer . it is not collection .
So, you will get compiler error.

No you won’t. Go 1.22 introduced range over integers.

This example I have from website I use to learn too
https://gobyexample.com/for

also I use golangbot.com but there is no range example there

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.