Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 809
Rick Smith Avatar asked Nov 14 '12 17:11

Rick Smith


1 Answers

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.

like image 174
Stephen Weinberg Avatar answered Nov 12 '22 19:11

Stephen Weinberg