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)
}
Hey all.
New programmer here.
I was wondering, when composing slices, specifically in a for/index/range situation, when it comes time to fmt.Println, is it bad practice to include a +1 in the index, so that when it prints it would do so starting at 1 as opposed to 0 for readability? Or is that blasphemous?
Thank you.