3 ms·
Decided to try in rust to test the behavior [0]: fn absolute(n: i8) -> i8 { if n >= 0 { n } else { -n } } fn main() { let nums = [
by dsQTbR7Y5mRHnZv 5y ago
Decided to try in rust to test the behavior [0]:
fn absolute(n: i8) -> i8 {
if n >= 0 { n } else { -n }
}
fn main() {
let nums = [i8::MIN, i8::MIN + 1, 0, i8::MAX - 1, i8::MAX];
for num in nums {
println!("{}", absolute(num));
}
}
Seems to cause a runtime error:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 3.57s
Running `target/debug/playground`
thread 'main' panicked at 'attempt to negate with overflow', src/main.rs:2:27
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[0] https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=73976b255a748c62749c691183bb14ec https://play.rust-lang.org/?version=stable&mode=debug&editio...
- tialaramex 5y agoThat's correct. Rust provides four versions of fundamental arithmetic for the integer types: * Checked where you get Some(answer) or None * Overflowing where you get (answer,false) or (overflowed_answer,true) * Saturating where you get answer or the closest of type:::MIN and type::MAX to the correct answer * Wrapping where the number line wraps around at the end If you don't pick which you wanted, but then you do something that's poorly defined a debug build will panic, whereas a production build wraps. The panic in debug is to encourage you to actually decide which of the four operations you meant and write that.