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.

RustData Integrity

Code

rustsnippet
19 lines
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

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| =`.