Rust If .. Else Conditions
Conditions and If..Else
You already know that Rust supports familiar comparison conditions from mathematics, such as:
- 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 a single expression, you can write it in a shorter way on one line:
Example
let time = 20;
let greeting = if time < 18 { "Good day." } else { "Good evening." };
println!("{}", greeting);
Try it Yourself »
Tip: This works similarly to the ternary operator (condition
? value1 : value2
) in languages like Java or C. However, Rust does not have a ternary operator, but using if...else
as an expression gives you the same effect.
Don't Mix Types
Note: The value from if
and else
must be the same type, like two pieces of text or two numbers (in the example above, both are strings).
When you mix types, like a string and an integer, you'll get an error:
Example
let number = 5;
let result = if number < 10 { "Too small" } else { 100 };
println!("{}", result);
Result:
error[E0308]: `if` and `else` have incompatible types