132. abs_diff — Subtract Without Caring Which Side Is Bigger
Subtracting two unsigned integers and the smaller one comes first? Instant panic. a.abs_diff(b) returns the gap as a u* regardless of which side is bigger — no branching, no overflow.
The Problem
Unsigned subtraction in Rust panics in debug and wraps in release the moment the result would go negative. You end up writing the same branch over and over:
| |
It works, but it’s noise. And the same trick on signed integers has a sneakier bug: i32::MIN.abs_diff(i32::MAX) overflows an i32 — the gap doesn’t fit in the signed range.
After: abs_diff
Every integer type carries an abs_diff method that returns the unsigned gap directly. Signed inputs come back as the matching unsigned type, so the result always fits:
| |
No if, no checked_sub, no casting through i64 to dodge overflow. One call, one number.
Where It Earns Its Keep
Distance-style calculations are the obvious fit — anywhere “how far apart are these” is the real question and the sign is incidental:
| |
It also cleans up timestamp deltas, where one side is “now” and the other could be in the past or the future:
| |
Whenever you catch yourself writing if a > b { a - b } else { b - a }, reach for abs_diff instead.