Unsigned Abs With abs_diff
Compute absolute differences with abs_diff so unsigned results never panic, and use unsigned_abs on i32 deltas before casting to usize.
Code
fn main() {
// abs_diff:i32 相减的绝对差直接落进 u32,不会 panic
let a: i32 = -7;
let b: i32 = 12;
let gap: u32 = a.abs_diff(b);
println!("gap: {gap}");
// 顺序颠倒结果一致:差值与方向无关
println!("reversed: {}", b.abs_diff(a));
// unsigned_abs:负数的绝对值以无符号表示,i32::MIN 也有精确答案
let floor: i32 = i32::MIN;
println!("|i32::MIN| = {}", floor.unsigned_abs());
// 手写 (a - b).abs() 的坑:i32::MIN 的取负在 debug 构建直接 panic
// abs_diff / unsigned_abs 是绕开溢出的官方路径
let drift: usize = (a as i64 - b as i64).unsigned_abs() as usize;
println!("drift as usize: {drift}");
}How it works
Unsigned Abs With abs_diff reduces to the function main.
Applying it
The demo output is labeled (gap:, reversed:, |i32::MIN| =), so every printed line maps back to its originating operation.
Statements that matter
let drift: usize = (a as i64 - b as i64).unsigned_abs() as usize;
let gap: u32 = a.abs_diff(b);
let floor: i32 = i32::MIN;
Interactive Tools for This Topic
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
FAQ
- What does Unsigned Abs With abs_diff print when run?
- Execute the whole file; each printed line is prefixed with a label like `gap:`, `reversed:`, `|i32::MIN| =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.