Introduction
If-else expressions help your program choose between two paths based on a condition. This lets your program make decisions like a person would.
If-else expressions help your program choose between two paths based on a condition. This lets your program make decisions like a person would.
let variable = if condition { value_if_true } else { value_if_false };
if and else parts are expressions that return values.if and else to assign a value to a variable.number is greater than zero and prints if it is positive or not.let number = 5; let result = if number > 0 { "positive" } else { "non-positive" }; println!("{} is {}", number, result);
can_vote to true if age is 18 or more, otherwise false.let age = 18; let can_vote = if age >= 18 { true } else { false }; println!("Can vote: {}", can_vote);
This program checks the temperature and prints if the weather is hot or cool.
fn main() {
let temperature = 30;
let weather = if temperature > 25 {
"hot"
} else {
"cool"
};
println!("The weather is {}.", weather);
}Remember, if and else in Rust are expressions, so they return values.
Every if must have an else if you want to assign the result to a variable.
If-else expressions let your program choose between two options.
They return values, so you can store the result in a variable.
Always include else when assigning the result to a variable.
if-else expression in Rust do?if condition { value1 } else { value2 } with braces and no parentheses.let number = 7;
let result = if number % 2 == 0 { "even" } else { "odd" };
println!("{}", result);let x = 10;
let y = if x > 5 { 1 };
println!("{}", y);grade based on a score: if score is 90 or above, grade is 'A', else 'F'. Which code correctly uses if-else expression?if condition { value } else { value } without 'then' or semicolons inside.Pass the test and this pattern moves unknown