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