Numeric casts and checked arithmetic
Quick answer
Numeric casts use as to convert a value to another numeric type. A cast can lose information, such as when a wide unsigned integer is narrowed. Checked arithmetic reports overflow rather than silently accepting an unrepresentable result.
Use an explicit overflow policy
For u8, a value must fit in 0 through 255. as narrowing discards high bits; u8::try_from instead reports failure if the integer does not fit. checked_add returns Some(value) when addition fits and None when it overflows. Some and None are the two forms of Option, taught in more depth later. The debug output below displays them without requiring pattern matching yet.
fn main() { let wide = 300u16; println!("Narrowed: {}", wide as u8); println!("Fits: {}", u8::try_from(wide).is_ok());}Expected stdout (not executed):
Narrowed: 44Fits: falseThe low eight bits represent 44; the fallible conversion refuses the loss. is_ok checks whether conversion succeeded.
fn main() { let count = 250u8; println!("{:?}", count.checked_add(3)); println!("{:?}", count.checked_add(10)); println!("{}", count.saturating_add(10));}Expected stdout (not executed):
Some(253)None255Saturating addition clamps to the maximum; it is a different policy from reporting overflow.
Common mistake
Do not rely on ordinary overflowing arithmetic always panicking or always wrapping. Behavior depends on overflow-check settings; select checked, wrapping or saturating methods deliberately.
Try it yourself
Predict the checked and saturating sums of 254u8 and 2. Explain which policy suits a count that must reject overflow.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric casts and checked arithmetic — practice quiz
Choose one answer per question, then review the explanation.
What does `256u16 as u8` produce?
What does `u8::try_from(256u16).is_ok()` return?
What does `253u8.saturating_add(9)` return?