简体   繁体   中英

rust overflow check on more integer operations in a row

How can I do overflow check in all steps of 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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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