248. is_multiple_of — Divisibility That Won't Panic on Zero
x % y == 0 is the divisibility check everyone writes — and it panics the moment y is zero. is_multiple_of says what you mean and returns false instead of blowing up.
The hidden panic in % == 0
The modulo idiom works until the divisor comes from outside your control — a config value, a user-supplied chunk size, a computed stride:
| |
A validation helper that itself crashes on bad input is exactly backwards.
is_multiple_of handles zero for you
Stable since Rust 1.87 on all unsigned integers:
| |
n.is_multiple_of(m) is true exactly when some k satisfies n == k * m. Zero is a multiple of everything (including zero), and nothing else is a multiple of zero. No branch you have to remember to write, no if block != 0 && guard cluttering the call site.
Reads like the sentence you meant
Even when the divisor can never be zero, the method wins on intent. Compare a leap-year-style rule:
| |
The name carries the meaning; the == 0 version makes every reader re-derive it. Clippy agrees — recent versions lint x % y == 0 as manual_is_multiple_of.
One caveat: it’s unsigned-only (u8 through u128, plus usize). For signed integers you’re still on % — pair it with a zero check yourself.