Consider the following Rust code snippet. What will it print when run in debug mode?
fn main() {
let x: u8 = 255;
let y = x + 1;
println!("{}", y);
}Think about what happens when you add 1 to the maximum value of an 8-bit unsigned integer in Rust debug mode.
In Rust debug mode, integer overflow causes a panic at runtime. So adding 1 to 255 (max u8) triggers a panic, not wrapping or printing 0.
What value does z hold after this Rust code runs?
fn main() {
let x: u8 = 250;
let y: u8 = 10;
let z = x.wrapping_add(y);
println!("{}", z);
}Wrapping addition means the value wraps around on overflow instead of panicking.
250 + 10 = 260, but u8 max is 255, so it wraps: 260 - 256 = 4.
In Rust, which integer type can store values from -32,768 to 32,767?
Think about signed 16-bit integers.
i16 is a signed 16-bit integer type with range -32,768 to 32,767.
What does this Rust program print?
fn main() {
let a = 1000;
let b: u16 = 500;
let c = a + b as i32;
println!("{}", c);
}Check how Rust handles integer types and casting in expressions.
Variable a is inferred as i32, b is u16 cast to i32, so addition works and prints 1500.
What error will this Rust code cause when compiled?
fn main() {
let x: i8 = 128;
println!("{}", x);
}Check the valid range for i8 and what happens when you assign a literal outside that range.
i8 can hold values from -128 to 127. 128 is out of range and causes a compile-time error.