Slices i+1 in a range clause
loops - Is there a way to iterate over a range of integers? - Stack Overflow
how counting up a variable in range from 1 to n,isn't start 0
Is there any way to keep the "range" action in a template from sorting keys?
What do you mean by "the doc"? The spec clearly says that ranging over maps is in an undefined order:
"The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are removed during iteration, the corresponding iteration values will not be produced. If map entries are created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0."
More on reddit.comHey 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.
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)
}
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)
}