I am writing a cycle method for a list that moves an index either forwards or backwards. The following code is used to cycle backwards:
(i-1)%list_length
In this case, i
is of the type usize
, meaning it is unsigned. If i
is equal to 0, this leads to an 'attempt to subtract with overflow' error. I tried to use the correct casting methods to work around this problem:
((i as isize)-1)%(list_length as isize)) as usize
This results in an integer overflow.
I understand why the errors happen, and at the moment I've solved the problem by checking if the index is equal to 0, but I was wondering if there was some way to solve it by casting the variables to the correct types.
(-1 % 10)
is-1
, not9
.-1isize as usize
is18446744073709551615
(on 64-bit architectures). – Gneiss