Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.
Sign upDecrementing range behaviour is very confusing when used with unsigned integers #14020
Comments
This comment has been minimized.
This comment has been minimized.
|
It's not a decrementing range. The type of |
thestinger
closed this
May 7, 2014
This comment has been minimized.
This comment has been minimized.
|
@thestinger This does expose an interesting problem with the range_step function, though. As far as I'm concerned, the primary usecase is to do reverse iteration (which seems to have been deemed "confusing" for the range function to support), for which you need range_step(,,-1). Thus, all of the arguments have to be signed. However, if I want to iterate over unsigned integers, I can't reasonably always convert them to signed integers. One would reasonably expect to be able to iterate from uint::MAX to uint::MIN, but as it stands, none of the range functions seem to permit this. Or am I mistaken? Edit: I mean, you can just use range().rev() to accomplish this, but it's odd that that's necessary. |
This comment has been minimized.
This comment has been minimized.
|
@Gankro: Reverse iteration with a step of 1 can be done with |
pimterry commentedMay 7, 2014
Range behaviour differs significantly and unexpectedly from expected behaviour if the range start is an unsigned integer.
This prints 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.
(range_start is a uint, not an int)
This prints '10', and stops. This is not expected.
This appears to be because the type signature for range_step uses the same generic parameter for all three argument. Thus, if the start is a uint then the others are all interpreted as uints, the negative numbers are interpreted as very large ints, the range increments by 2^64-1 up to a max of 2^64-1, rather than decrementing by -1, and the range immediately finishes.
This seems like a relatively common operation, and it'd be nice if the rust compiler could catch the incorrect types in this code, and/or the range_step method could properly handle mixing signed and unsigned parameters to the method.
(N.b. I am relatively new to rust, sorry if there's something obvious I'm missing that invalidates this entirely)