#248 Jul 8, 2026

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:

1
2
3
4
5
6
fn fits_evenly(len: usize, block: usize) -> bool {
    len % block == 0
}

fits_evenly(12, 4); // true
fits_evenly(12, 0); // panic: remainder with a divisor of zero

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:

1
2
3
4
5
6
assert!(12_u32.is_multiple_of(3));
assert!(!13_u32.is_multiple_of(3));

// No panic — just the mathematically honest answer:
assert!(!12_u32.is_multiple_of(0));
assert!(0_u32.is_multiple_of(0)); // 0 = 0 * anything

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let year = 2026_u32;

// Which of these is the "divisible" and
// which is the "not divisible" arm again?
let a = year % 4 == 0 && year % 100 != 0;

let b = year.is_multiple_of(4)
    && !year.is_multiple_of(100);

assert_eq!(a, b);
assert!(!b); // 2026: not a leap year

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.

← Previous 247. sort_unstable — Skip the Allocation When Ties Don't Matter Next → 249. bit_width — How Many Bits Does This Number Need? (New in Rust 1.97)