Rust Nested If
Nested If
You can put an if statement inside another if statement. This is called a nested if.
It is useful when a second question only matters if the answer to the first one is yes. For example, a concert only checks your ticket if you are old enough to enter:
Example
let age = 20;
let has_ticket = true;
if age >= 18 {
println!("You are old enough.");
if has_ticket {
println!("Welcome to the concert!");
} else {
println!("You need a ticket.");
}
} else {
println!("You are too young.");
}
Try it Yourself »
Example explained
- The outer
ifchecks the age.20 >= 18istrue, so it prints "You are old enough." - Then the inner
ifchecks the ticket.has_ticketistrue, so it prints "Welcome to the concert!" - If
agewas16, the innerifwould never run. The program would only print "You are too young."
Use && Instead
When you only need one answer, you can often replace a nested if with the && (AND) operator from the Operators chapter. The condition is only true if both parts are true:
Example
let age = 20;
let has_ticket = true;
if age >= 18 && has_ticket {
println!("Welcome to the concert!");
} else {
println!("You cannot enter.");
}
Try it Yourself »
This is shorter, but the program can no longer tell the visitor why they cannot enter. Use a nested if when each step needs its own message.
Use || for Either
The || (OR) operator is true if at least one of the conditions is true:
Example
let day = "Saturday";
if day == "Saturday" || day == "Sunday" {
println!("It is the weekend!");
} else {
println!("It is a weekday.");
}
Try it Yourself »
Use ! for Not
The ! (NOT) operator turns true into false, and false into true:
Example
let is_raining = false;
if !is_raining {
println!("Let's go for a walk.");
}
Try it Yourself »
Tip: Try not to nest too deep. Code with many levels of if inside if is hard to read. Often, &&, || or else if can make it flatter.