expression
Rust Narrowing integer casts and checked alternatives
An explicit integer cast can lose information when the destination is too small. Use a checked conversion when an out-of-range value should be rejected. Expected output (not executed): 44 true Why: Only the lowest eight bits remain in the cast; the checked conversion reports failure. Common mistake: Do not assume `as` validates whether the source fits.
Formal Syntax & Structure
rust syntaxrust
value as u8; u8::try_from(value)Working Example
Example Snippetrust
fn main() { let count = 300_u16; println!("{}", count as u8); println!("{}", u8::try_from(count).is_err());}