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.