Go - uint32 in for loop condition (mismatched types int and uint32)

go, type-conversion

Solution

You can do:

for i := uint32(0); i < size; {
    //whatever
}

Generally, I don't recommend using an unsigned integer even when size can never be negative. I don't know of any upside. I only use unsigned integers when I am intentionally overflowing.

Problem

For the sake of type strictness I sometimes store my sizes as uint's when a size cannot be negative. When used in for loops, I want it to look like this: ``` var size uint32 = 8 for i := 0; i < size; { n := //doesn't matter how how this value is determined i += n } ``` However, I get the following error message: `invalid operation: i < size (mismatched types int and uint32)` Rewriting the for loop to specify a type like this: ``` for var i uint32 = 0; i < size; { ``` Yields this compiler error: `syntax error: var declaration not allowed in for initializer` The only ways around these errors are: ``` for i := 0; uint32(i) < size; { ``` or ``` var i uint32 = 0 for i < size { ``` The first on is inefficient because I am casting on every iteration and the second one is less elegant. Is there a better way to do this?

Original source