API and Numeric Boundaries · 14 min · free with an account

Integer Boundaries and Conversion

Lesson preview · about 30%

Input bounds and arithmetic policy are part of the algorithm’s contract.

Core idea

Choose the numeric domain and overflow policy explicitly, and widen before the operation when that is the proof.

Start with the idea

Integer operations need a policy when the mathematical result is outside the destination range. checked_add returns None on overflow, wrapping_add uses modular arithmetic, and saturating_add clamps at a boundary. A lossy as conversion can discard information; TryFrom can reject an out-of-range conversion. Choose behaviour that matches the domain instead of depending on the build’s overflow-check settings.

The example checks an addition at u32::MAX and rejects narrowing 300 to u8. It also widens i32 operands before computing their difference. Widening after an overflowing operation is too late.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep