Back to questions
JuniorTheoryCommon
What does the program print?
fn main() {
let n = 300_i32;
println!("{}", n as u8);
}44
- Expecting
255: anascast between integers does not stop at the largest value; it keeps what fits in 8 bits, and 300 − 256 = 44. - Expecting a panic, as with overflow in a debug build:
asnever checks the range, it truncates silently.
- How would you convert 300 to
u8so that the failure is reported, not hidden? - What does
-1_i32 as u8give, and why?