A function I have takes min, max uint16
parameters and at some point iterates over the numeric range. However, if max happens to be 2^16-1 (and it is a valid use case), then overflow breaks the loop logic. Here is an example code demonstrating the problem with uint8
:
package main
import "fmt"
func iter(min, max uint8) {
for i := min; i <= max; i++ {
fmt.Printf("%d, ", i)
}
}
func main() {
iter(0, 255)
}
As you can see, the program never ends. A similar question was asked at another question but the solution exactly exhibits the same problem I have.
My thinking for now is to convert the loop variable to uint32
, similar to this:
package main
import "fmt"
func iter(min, max uint8) {
for i := uint16(min); i <= uint16(max); i++ {
fmt.Printf("%d, ", i)
}
}
func main() {
iter(0, 255)
}
However, this seems to be a clumsy solution, which is not going to work for uint64
or whatever biggest uintN
type. Feels like I am missing something very basic. Guidance?
I am aware of Brad Fitz's Iter solution, but it seems to add unneeded overhead. Is that true as well?