Introduction
Using if as an expression lets you choose a value based on a condition in one simple step.
Using if as an expression lets you choose a value based on a condition in one simple step.
let variable = if condition { value_if_true } else { value_if_false };
The if block returns a value, so you can assign it directly.
Both branches must return the same type of value.
result to "positive" because number is 5.let number = 5; let result = if number > 0 { "positive" } else { "non-positive" };
can_vote to true because age is 18 or more.let age = 18; let can_vote = if age >= 18 { true } else { false };
if expressions.let score = 75; let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };
This program checks the temperature and sets weather to "hot" or "cool" using if as an expression, then prints the result.
fn main() {
let temperature = 30;
let weather = if temperature > 25 {
"hot"
} else {
"cool"
};
println!("The weather is {}.", weather);
}Remember to end the if expression with a semicolon if you assign it to a variable.
All branches must return the same type, or Rust will give an error.
if can be used to pick a value based on a condition.
This helps write shorter and clearer code.
Make sure all branches return the same type.
if as an expression in Rust allow you to do?if can return a value, unlike some languages where it only controls flow.let x = if condition { value1 } else { value2 };.if as an expression to assign a value in Rust?if condition { 10 } else { 20 };. Others use invalid syntax like missing braces or keywords.let number = 7;
let result = if number % 2 == 0 { "even" } else { "odd" };
println!("{}", result);let x = if true { 5 } else { "five" };status based on a score: if score >= 90, status is "Excellent"; if score >= 60, status is "Pass"; otherwise, "Fail". Which Rust code correctly uses nested if expressions to do this?if and else if expressions to select among multiple conditions.else if and ends with else block. let status = if score >= 90 { "Excellent" } else { if score >= 60 { "Pass" } else { "Fail" } }; nests if inside else but is more verbose. Options C and D have syntax errors.Pass the test and this pattern moves unknown