Skip to main content

How to Use an if Statement in Rust

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

An if in Rust runs a block of code only when a condition is true. else if adds more conditions, checked in order, and else runs when none of them was true. The condition must be a bool: Rust doesn't treat a number as true or false.

Syntax​

Syntax
if <condition> {
<code>
} else if <condition> {
<code>
} else {
<code>
}
PartWhat it does
if <condition>Runs the block after it when the condition is true, and skips the rest.
else if <condition>Optional, and you can have several. Checked only when every condition above it was false.
elseOptional. Runs when no condition was true.
<condition>An expression of type bool, such as amount > limit. It needs no parentheses.
<code>The code to run, always inside braces, even when it's one line.

The Rust Book, if Expressions: "An if expression allows you to branch your code depending on conditions." It adds: "the condition in this code must be a bool. If the condition isn't a bool, we'll get an error."

The Example​

The example defines a function, check, that compares an order amount with a limit of 500 and prints whether the amount is over the limit, exactly at it, or under it. It calls the function with 900, 500 and 120, so each branch runs once. Then a changed version uses a number as a condition.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, with a check function that compares an amount with a limit of 500 using if, else if and else and prints over, exactly at or under the limit, and a main that checks 900, 500 and 120.

src/main.rs
fn check(amount: u32) {
let limit = 500;
if amount > limit {
println!("{amount}: over the limit");
} else if amount == limit {
println!("{amount}: exactly at the limit");
} else {
println!("{amount}: under the limit");
}
}

fn main() {
check(900);
check(500);
check(120);
}

fn check(amount: u32) defines a function that takes the amount, and main calls it three times. {amount} inside the text prints the amount in front of each message.

Step 2: Run It​

Terminal
cargo run -q
Output
900: over the limit
500: exactly at the limit
120: under the limit

-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.

Step 3: Use a Number as the Condition​

Replace src/main.rs with a version whose condition is a number of items, not a comparison:

src/main.rs
fn main() {
let items = 3;
if items {
println!("the cart has items");
}
}
Terminal
cargo run -q
Output
error[E0308]: mismatched types
--> src/main.rs:3:8
|
3 | if items {
| ^^^^^ expected `bool`, found integer

For more information about this error, try `rustc --explain E0308`.
error: could not compile `demo` (bin "demo") due to 1 previous error

A zsh terminal where cargo run -q prints 900 over the limit, 500 exactly at the limit and 120 under the limit, then, for the changed file, fails with error E0308, mismatched types, expected bool, found integer.

What Happened​

  • 900 is over 500, so the if branch ran.
  • 500 isn't over 500, so Rust checked the else if next, and amount == limit was true.
  • 120 matched neither condition, so the else branch ran.
  • Only one branch ran each time. The Rust Reference, if expressions: when a condition is true, "the consequent block is executed and any subsequent else if or else block is skipped."
  • A number isn't a condition. The changed version didn't compile: Rust expected a bool and found an integer. The Book: "Unlike languages such as Ruby and JavaScript, Rust will not automatically try to convert non-Boolean types to a Boolean." Comparing the number fixes it: if items > 0 printed the cart has items.

Common Mistakes​

MistakeWhat happensDo this instead
A number as the condition, as in if itemserror[E0308]: mismatched types: expected bool, found integerCompare it, as in if items > 0
= instead of ==, as in if amount = limiterror[E0308]: mismatched types: expected bool, found (), with the help "you might have meant to compare for equality"Use == to compare
Leaving out the braces, as in if amount > 500 println!("over the limit");error: expected `{`, found `println`Put the code inside braces
Writing elseif as one wordhelp: there is a keyword `else` with a similar name, and the code it suggests fails too, as shown in this fixWrite else if
Parentheses around the condition, as in if (amount > 500)It works, with warning: unnecessary parentheses around `if` conditionLeave the parentheses out

Troubleshooting​

SymptomLikely causeFix
error[E0317]: `if` may be missing an `else` clauseAn if used as a value has no elseAdd an else branch that gives a value of the same type
error[E0308]: `if` and `else` have incompatible typesThe branches of an if used as a value give different types, such as "denied" and 0Make every branch give the same type
expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `amount`elseif, elsif or elif instead of else ifWrite else if

FAQ​

Is if a statement or an expression in Rust?​

An expression: it can give a value. The Book: "Because if is an expression, we can use it on the right side of a let statement to assign the outcome to a variable". In my check, let status = if amount > limit { "denied" } else { "allowed" }; set status to denied for an amount of 900. Every branch must then give the same type, and an else is required.

Do I need parentheses around the condition?​

No. They work, but the compiler warns warning: unnecessary parentheses around `if` condition and suggests removing them.

Conclusion​

if, else if and else pick one block to run, checking the conditions from the top. Give each one a real bool, such as a comparison, put every block in braces, and use if as an expression when you need a value.

Additional Resources​