Consider this Rust code snippet. What will it print?
fn main() {
let x = 7;
let y = if x > 5 { "big" } else { "small" };
println!("{}", y);
}Remember, the if expression returns a value based on the condition.
The variable y is assigned the string "big" because x is 7, which is greater than 5.
In Rust, when using an if expression to assign a value, what must be true about the types of the values in the if and else branches?
Think about how Rust enforces type safety.
Rust requires both branches of an if expression to have the same type so the compiler knows the type of the whole expression.
Analyze the following Rust code and select the output it produces.
fn main() {
let a = 10;
let b = 20;
let max = if a > b { a } else { b };
println!("{}", max);
}The if expression chooses the bigger number.
Since b (20) is greater than a (10), the else branch runs and max is 20.
Look at this Rust code snippet. What error will the compiler show?
fn main() {
let x = 5;
let y = if x > 3 { 10 } else { "small" };
println!("{}", y);
}Check the types returned by each branch of the if expression.
The if branch returns an integer (10), but the else branch returns a string ("small"). Rust requires both branches to have the same type, so it raises a type mismatch error.
Consider this Rust code using an if expression inside a vector initialization. How many elements does the vector v have?
fn main() {
let condition = true;
let v = vec![1, 2, if condition { 3 } else { 4 }];
println!("{}", v.len());
}Count all elements added to the vector.
The vector v contains three elements: 1, 2, and either 3 or 4 depending on the condition. Since the condition is true, the third element is 3, so the length is 3.