An order of $100 or more gets free delivery. Below that, delivery costs $10. The delivery rule at Rusdi's Pancake Stall is just two lines, each order matches exactly one of them, and the result is always an amount of dollars written on the receipt.
In code, a rule like this is written with if. if picks a path depending on a condition, something whose value is true or false, here total >= 100. The two delivery rules become two branches: the if branch for when the condition is true, the else branch for everything else. In Rust, if is also an expression: it produces the value of the branch that is chosen, like the delivery amount on the receipt. So its result can be stored right away in a variable.
if, else if, else
This program picks one of three delivery messages:
fn main() {
let total: u32 = 32 * 2 + 38 * 1;
if total >= 100 {
println!("Free delivery");
} else if total >= 50 {
println!("Delivery 5");
} else {
println!("Delivery 10");
}
}
Two Sweet Pancakes and one Egg Pancake cost 102 in total, so the output is Free delivery.
- The condition is written without brackets.
if (total >= 100)still runs, but gets the warningunnecessary parentheses around `if` condition(the brackets around the condition are not needed). - Curly braces
{ }are required, even when the body is one line. - Conditions are checked from the top. The first branch whose condition is true runs, and the other branches are skipped.
elsecatches everything that didn't match, and may be left out. - Comparisons:
==equal,!=not equal,<,>,<=,>=. Combiners:&&(and),||(or),!(not). For example,total >= 100 && !membermeans the total is at least 100 and the buyer is not a member (memberhere is aboolvariable).
The condition must be a bool
In JavaScript, if (portions) runs for any number other than 0 and NaN. In Rust, the condition must have the type bool (true or false). If portions is a u32, if portions is refused:
error[E0308]: mismatched types
--> src/main.rs:3:8
|
3 | if portions {
| ^^^^^^^^ expected `bool`, found `u32`
Write the comparison out: if portions > 0. The same happens if you type = (fill) where you meant == (compare). if portions = 2 is refused with expected `bool`, found `()` and the suggestion you might have meant to compare for equality.
if as an expression
In this program, the result of if is stored right away in the variable delivery:
fn main() {
let total: u32 = 32 * 1 + 38 * 1;
let delivery = if total >= 100 { 0 } else { 10 };
println!("Subtotal: {}", total);
println!("Delivery: {}", delivery);
println!("Due: {}", total + delivery);
}
The output:
Subtotal: 70
Delivery: 10
Due: 80
if total >= 100 { 0 } else { 10 }produces the value of the chosen branch. 70 hasn't reached 100, sodeliveryholds10.- The value inside a branch is written without a semicolon, just like a function's last line. The semicolon goes at the end of the
letline. - This replaces
condition ? a : bfrom JavaScript, the operator that picks the valueaorb. Rust has no? :operator, becauseifcan already produce a value.
Both branches must have the same type
The cashier wants the receipt to say the word "free", so they write let delivery = if total >= 100 { "free" } else { 10 };. Does this code compile? Guess before you read on.
The problem is that delivery may only have one type. If one branch produces text and the other a number, the compiler can't choose:
error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:3:54
|
3 | let delivery = if total >= 100 { "free" } else { 10 };
| ------ ^^ expected `&str`, found integer
| |
| expected because of this
The first branch sets the type (&str), then the second branch (a number) is refused. So the answer is no, it doesn't compile. Use 0 in the first branch, then write the word "free" when printing.
One more rule: an if whose result is stored must have an else. let delivery = if total >= 100 { 0 }; is refused with error[E0317]: `if` may be missing an `else` clause. The reason: without else, there is no value for delivery when the condition is false.
The order of conditions decides the result
A function can also hand over text written straight into the code. Its return type is &'static str: fixed text that exists as long as the program runs. The function below gives a delivery label, but its conditions are in the wrong order:
fn delivery_label(total: u32) -> &'static str {
if total >= 50 {
"cheap"
} else if total >= 100 {
"free"
} else {
"normal"
}
}
fn main() {
println!("{}", delivery_label(102));
}
The output is cheap, even though an order of 102 should be free. 102 already passes >= 50 in the first branch, so the >= 100 branch is never checked. That branch can never be chosen, and the compiler doesn't warn about it. Check from the highest limit first: >= 100, then >= 50, then else.
⚠️ Why is your if refused, or picking the wrong branch?
- A condition that isn't a bool.
if portionsis refused. Writeif portions > 0. - Branches of different types. Every branch of an
ifwhose result is used must produce the same type. - A semicolon inside a branch.
if total >= 100 { 0; } else { 10 }is refused withexpected `()`, found integer:0;is already a statement, which hands over(). - The order turned around. A looser condition at the top, like
>= 50, swallows a stricter one below it, like>= 100.
TL;DR: if condition { } else if condition { } else { } is checked from the top, and only the first branch ({ } block) whose condition is true runs. The condition is written without brackets and must be a bool (true or false). Rust has no truthy values as JavaScript does, where any number other than 0 and NaN counts as true. Curly braces are required too. if is an expression (code that produces a value): let delivery = if total >= 100 { 0 } else { 10 }; stores the value of the chosen branch. An if whose result is stored must have an else, all its branches must have the same type (`if` and `else` have incompatible types), and its values are written without semicolons. A function that hands over text written straight into the code has the return type &'static str. Order the conditions from the highest limit down.
⚡ Checked from the top
Write:
if total >= 100 {
println!("Free delivery");
} else if total >= 50 {
println!("Delivery 5");
} else {
println!("Delivery 10");
}
Meaning: if picks a branch (a { } block) depending on a condition of type bool, such as total >= 100 (total is the order total). The condition is written without brackets, and curly braces are required. Conditions are checked from the top, and the first branch whose condition is true runs, so order them from the highest limit. If portions is a number, if portions is refused because it isn't a bool: write if portions > 0.
⚡ if produces a value
Write:
let delivery = if total >= 100 { 0 } else { 10 };
Meaning: Unlike JavaScript, if in Rust is an expression, code that produces a value: the value of the chosen branch is stored right away in delivery. If total is 100 or more, delivery holds 0. If it is less, 10. The value in a branch has no semicolon, and Rust needs no ? : operator from JavaScript.
⚡ One type for every branch
Guess first: does let delivery = if total >= 100 { "free" } else { 10 }; compile?
No. The first branch is text, the second a number, so the compiler refuses with `if` and `else` have incompatible types.
Meaning: A variable has only one type, so every branch must have the same type. An if whose result is stored must also have an else, so there is still a value when the condition is false.