If-Else
Part of the Fundamentals section of Coddy's Rust journey — lesson 25 of 75.
if allows us to execute particular code if a condition is met, but what if we want to execute something else if the condition is not met?
For that we have the else statement:
let age: i32 = 15;
let status = if age >= 18 {
"Adult"
} else {
"Young"
};In the above example, age is smaller than 18 which means it enters the else code and status will hold "Young".
We can even make it more profound using the else if statement:
let age: i32 = 68;
let status = if age < 18 {
"Young"
} else if age >= 18 && age <= 65 {
"Adult"
} else {
"Old"
};Here it checks whether age is smaller than 18, if not it will continue to the next condition and check whether age is between 18 and 65. If that condition is also not met it will set status to "Old".
We can add as many else if statements as we want:
if condition1 {
code;
} else if condition2 {
code;
} else if condition3 {
code;
}
...Challenge
BeginnerYou are given a code which gets as input a number that indicates the wind speed and stores it in a variable named wind.
Note: we will learn in next lessons how to get input from the user, currently just don't touch the first lines.
Your task is to initialize variable status based on the conditions:
"Calm"ifwindis smaller than8,"Breeze"ifwindis between8and31(including 8 and 31)."Gale"ifwindis between32and63(including 32 and 63)"Storm"otherwise
Check the test cases to see all the inputs and the expected outputs
Cheat sheet
Use else to execute code when the if condition is not met:
let age: i32 = 15;
let status = if age >= 18 {
"Adult"
} else {
"Young"
};Use else if to check multiple conditions:
let age: i32 = 68;
let status = if age < 18 {
"Young"
} else if age >= 18 && age <= 65 {
"Adult"
} else {
"Old"
};You can chain multiple else if statements:
if condition1 {
code;
} else if condition2 {
code;
} else if condition3 {
code;
}Try it yourself
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let wind: i32 = input.trim().parse().unwrap();
// Replace the line below with an if-else expression that assigns status based on wind
let status = "unset";
// Don't change the line below
println!("status = {}", status);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input