Rust If .. Else Conditions
Conditions and If..Else
You have already learned that Rust supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Rust has the following conditional statements:
- Use
if
to specify a block of code to be executed, if a specified condition istrue
- Use
else
to specify a block of code to be executed, if the same condition isfalse
- Use
else if
to specify a new condition to test, if the first condition isfalse
- Use
switch
to specify many alternative blocks of code to be executed
Note: Unlike many other programming languages, if..else
can be used as a statement or as an expression (to assign a value to a variable) in Rust. See an example at the bottom of the page to better understand it.
if
Use if
to specify a block of code to be
executed if a condition is true
.
You can also test variables:
if...else
If the condition is not true, you can use else
to run different code:
Example
let age = 16;
if age >= 18 {
println!("You can vote.");
} else {
println!("You are too young to vote.");
}
Try it Yourself »
else if
You can check multiple conditions using else if
:
Example
let score = 85;
if score >= 90 {
println!("Grade: A");
} else if score >= 80 {
println!("Grade: B");
} else if score >= 70 {
println!("Grade: C");
} else {
println!("Grade: F");
}
Try it Yourself »
Using if
as an Expression
In Rust, if...else
can also be used as an expression.
This means you can assign the result of an if
to a variable:
Example
let time = 20;
let greeting = if time < 18 {
"Good day."
} else {
"Good evening."
};
println!("{}", greeting);
Try it Yourself »
When using if
as an expression, you must
include else
. This ensures the result always has a value.
Simplified Syntax
If each block only contains one line, you can remove the curly braces {}
and write it in a shorter way:
Example
let time = 20;
let greeting = if time < 18 { "Good day." } else { "Good
evening." };
println!("{}", greeting);
Try it Yourself »
Note: The value from if
and else
must be the same type, like two pieces of text or two numbers (in our example, both are strings).
Tip: This example works similarly to the ternary operator (short-hand if...else
) in languages like Java or C.