通过列表向后循环时对“尝试用溢出减去"感到恐慌 [英] Panicked at 'attempt to subtract with overflow' when cycling backwards though a list

查看:45
本文介绍了通过列表向后循环时对“尝试用溢出减去"感到恐慌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个向前或向后移动索引的列表编写循环方法.以下代码用于向后循环:

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

在这种情况下,iusize 类型,这意味着它是无符号的.如果 i 等于 0,这会导致尝试减法溢出"错误.我尝试使用正确的转换方法来解决此问题:

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

这会导致整数溢出.

我明白为什么会发生错误,目前我已经通过检查索引是否等于 0 来解决问题,但我想知道是否有某种方法可以通过将变量转换为正确的类型来解决它.

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.

推荐答案

As 丹麦克朗.指出,你不想在整数级别包装语义:

As DK. points out, you don't want wrapping semantics at the integer level:

fn main() {
    let idx: usize = 0;
    let len = 10;

    let next_idx = idx.wrapping_sub(1) % len;
    println!("{}", next_idx) // Prints 5!!!
}

相反,您想使用模逻辑来环绕:

Instead, you want to use modulo logic to wrap around:

let next_idx = (idx + len - 1) % len;

这仅在 len + idx 小于类型的最大值时才有效——使用 u8 更容易看到这一点usize;只需将 idx 设置为 200 并将 len 设置为 250.

This only works if len + idx is less than the max of the type — this is much easier to see with a u8 instead of usize; just set idx to 200 and len to 250.

如果您不能保证两个值的总和始终小于最大值,我可能会使用检查"系列操作.这与您已经提到的条件检查级别相同,但整齐地绑定到一行中:

If you can't guarantee that the sum of the two values will always be less than the maximum value, I'd probably use the "checked" family of operations. This does the same level of conditional checking you mentioned you already have, but is neatly tied into a single line:

let next_idx = idx.checked_sub(1).unwrap_or(len - 1);

这篇关于通过列表向后循环时对“尝试用溢出减去"感到恐慌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆