Consider the following Rust code. What will it print?
fn main() {
let x = 5;
let y = {
let z = x + 1;
z * 2
};
println!("{}", y);
}Remember that blocks in Rust can be expressions returning the last value without a semicolon.
The block assigns z = x + 1 which is 6, then returns z * 2 which is 12. This value is assigned to y.
Identify which option is a statement rather than an expression.
Statements perform actions but do not return values.
let x = 10; is a statement that declares a variable. The others are expressions that produce values.
Examine the code and select the reason for the compilation error.
fn main() {
let x = 5;
let y = if x > 3 {
x + 1;
} else {
x - 1
};
println!("{}", y);
}Check the effect of semicolons on expressions inside if blocks.
The semicolon after x + 1 turns that expression into a statement returning unit (). The else branch returns x - 1 (an integer), so the branches have mismatched types.
Choose the correct Rust code that assigns y using an expression block.
Remember that the last expression in a block without a semicolon is the block's value.
Option C returns a + 4 as the block's value. Option C has a semicolon making the block return unit (). Option C uses return inside a block which is invalid here. Option C returns unit because println! returns unit.
Analyze the code and determine the final value of z.
fn main() {
let x = 2;
let y = {
let a = x * 3;
a + 1
};
let z = if y > 6 {
y * 2
} else {
y / 2
};
println!("{}", z);
}Calculate step-by-step: block value, then if condition, then final assignment.
y is a + 1 where a = 2 * 3 = 6, so y = 7. Since y > 6 is true, z = y * 2 = 14.
