Rust If Else
Up to now our programs did every step, top to bottom, every time. Real programs make choices. If it is raining, take an umbrella. If the password is right, open the account. In Rust you make choices with if.
fn main() {
let temperature = 35;
if temperature > 30 {
println!("It is hot. Drink some water!");
}
println!("Have a nice day.");
}It is hot. Drink some water! Have a nice day.
After if comes a condition, which must be a bool. If it is true, the code in the curly brackets runs. If it is false, Rust skips that block and carries on below it. There are no round brackets around the condition in Rust; you just write it.
else and else if
else gives the program something to do when the condition is false. With else if you can check several conditions in order. Rust tries them from the top and runs the first block whose condition is true, then skips all the rest.
fn main() {
let marks = 72;
if marks >= 90 {
println!("Excellent!");
} else if marks >= 60 {
println!("Good work.");
} else if marks >= 40 {
println!("You passed.");
} else {
println!("Let us practise a bit more.");
}
}Good work.
72 is not 90 or more, so the first block is skipped. It is 60 or more, so Rust prints the second message, and the other checks are never even looked at.
if gives a value
Here is something lovely about Rust: if is an expression, which means it can produce a value. You can use it on the right side of let, a bit like asking a question and keeping the answer.
fn main() {
let age = 15;
let ticket = if age < 12 { "child" } else if age < 18 { "teen" } else { "adult" };
println!("You need a {} ticket.", ticket);
let number = 7;
let kind = if number % 2 == 0 { "even" } else { "odd" };
println!("{} is {}", number, kind);
}You need a teen ticket. 7 is odd
Notice that there is no semicolon after "child", "teen" and "adult". A value without a semicolon at the end of a block is the value that block gives back. All branches must give the same type, so Rust always knows what ticket will be.
Practice exercises
- Write a program that prints whether a number is positive, negative or zero.
- Use
ifas an expression to set afeeto 50 for members and 80 for everyone else. - Write a grade program with at least four
else ifbranches and test it with several marks.