I am writing a loop method for a list that moves the index forward or backward. The following code is used to loop backward:
(i-1)%list_length
In this case, i is of type usize , that is, it has no sign. If i is 0, this results in an "attempt to subtract with overflow" error. I tried using the right casting methods to get around this problem:
((i as isize)-1)%(list_length as isize)) as usize
This leads to overflow of integers.
I understand why errors occur, and at the moment I solved the problem by checking if the index is 0, but I was wondering if there was any way to solve it by translating the variables into the correct types.
integer-overflow rust integer-arithmetic
blackplant
source share