简体   繁体   English

Rust 溢出检查连续更多的整数运算

[英]rust overflow check on more integer operations in a row

How can I do overflow check in all steps of a如何在 a 的所有步骤中进行溢出检查

fn somemath() -> u32 {
   let x: u32 = y * 3 + 2;
   return x
}

something similar to类似于

fn somemath() -> u32 {
    let x: u32 = y.checked_mul(3).checked_add(2)
    return x
}

Or what is the best practice, to avoid overflow in such cases?或者在这种情况下避免溢出的最佳做法是什么? In the end I need x to be not producing overflow and be a valid result or produce error and can the function return u32 if successfull?最后我需要 x 不产生溢出并且是一个有效的结果或产生错误,如果成功,函数可以返回 u32 吗?

It's up to you to decide whether the check is necessary, and what do do when it overflows.由您决定是否需要检查,以及当它溢出时怎么办。

If there's no meaningful result if the overflow happens, you can return Option::None for example:如果发生溢出时没有有意义的结果,您可以返回Option::None例如:

fn somemath(y: u32) -> Option<u32> {
    let x: u32 = y.checked_mul(3)?.checked_add(2)?;
    return Some(x);
}

fn somemath(y: u32) -> Option<u32> {
    y.checked_mul(3)?.checked_add(2) // same, but shorter
}

You could also check whether inputs are small enough that overflow will never happen.您还可以检查输入是否足够小以至于永远不会发生溢出。 Or you could use a larger type for intermediate values (eg u64 here) to get a valid result for any u32 input.或者您可以对中间值使用更大的类型(例如这里的u64 )以获得任何u32输入的有效结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM