From Go 1.22 (expected release February 2024), you will be able to write:
for i := range 10 {
fmt.Println(i+1)
}
(ranging over an integer in Go iterates from 0 to one less than that integer).
For versions of Go before 1.22, the idiomatic approach is to write a for loop like this.
for i := 1; i <= 10; i++ {
fmt.Println(i)
}
Answer from Paul Hankin on Stack OverflowFrom Go 1.22 (expected release February 2024), you will be able to write:
for i := range 10 {
fmt.Println(i+1)
}
(ranging over an integer in Go iterates from 0 to one less than that integer).
For versions of Go before 1.22, the idiomatic approach is to write a for loop like this.
for i := 1; i <= 10; i++ {
fmt.Println(i)
}
It was suggested by Mark Mishyn to use slice but there is no reason to create array with make and use in for returned slice of it when array created via literal can be used and it's shorter
for i := range [5]int{} {
fmt.Println(i)
}
iterating over an integer?
language lawyer - How to iterate an integer in for-range loop in Go 1.22? - Stack Overflow
Preview: ranging over functions in Go
Iterate over Integers
Videos
so there's an upcoming feature where you can do for x := range n where n is an integer value. is that an attempt at avoiding a range syntax like Swift, Rust, and others have (m..n or m..=n or [m..n] or m...n) while at the same time having some thing that may in some sense resemble it? what are the possible uses of this construct? what is the rationale behind adding this to the language?
EDIT: what I find weird is that int is a scalar type in Golang, as I understand it, so how can you iterate over it. I mean semantically you cannot. but this is just simple syntactic sugar. I now get that this is a shorthand for one particular and popular case of C-derived for loop scheme where you routinely type out for i := 0; i < n; i++. so you can now just say for i := range n instead. no biggie. it's a very small thing to me.
if this saves someone a search, cool.