Rust: checked_sub & unwrap_or
Just a quick note for these two functions I learned today.
checked_sub
is used to check if the abstraction of an integer overflows. For example:
1 | let mut num_u32: u32 = 0; |
To prevent it, we can use the combo of checked_sub
and unwrap_or
. checked_sub
will return Option<self>
which means if there is no overflow occurs, we get Some(substraction_result)
, else we will get None
. unwarp_or
can then give the result a default value if we get None
or just unwrap Some(substraction_result)
to return substraction_result
. Let’s look at the code.
1 | let mut num_i32 = i32::MIN + 1; // -2147483648 + 1 |
That’s it for today!