1. if Is an Expression That Returns a Value
By default, a program runs line by line from top to bottom. In real programs, though, you often need to run different code or pick a different value depending on the situation.
A conditional (if) is the syntax that splits execution into separate paths.
In Part 2, we saw that an expression evaluates to a value, while a statement only performs an action.
In C and Java, if is a statement: it picks which code to run. To choose a value in an expression, use the ternary operator ?:.
Rust does not have a ternary operator. That is because if itself is an expression that returns a value.1
fn main() {
let count = 4;
let fee = if count > 3 { 6.0 } else { 12.0 };
println!("Shipping for {} items: ${}", count, fee);
}Output:
Shipping for 4 items: $6An order of four items makes count > 3 true. The first block yields 6.0, and the if expression assigns that value to the shipping fee, fee.
Order two items instead and the else block puts 12.0 into fee.
Notice that neither 6.0 nor 12.0 has a semicolon (;) after it inside the braces. Adding a semicolon turns an expression into a statement that evaluates to the empty unit value (()).
The semicolon at the very end of }; simply finishes the let fee = ...; variable declaration.
Both branches must yield the same type. If one supplies the float 6.0 and the other the string "free", the compiler cannot assign a single type to fee.
Leave out else, as in let fee = if count > 3 { 6.0 };, and the example won't compile. A false condition produces () because there is no block to run, while a true condition produces the float 6.0.
Second, the condition after if must strictly be a bool (true or false). Some languages automatically treat non-zero numbers as true, but Rust never allows that kind of implicit conversion.
Writing if count { ... } with a number fails to compile, so you must write an explicit comparison like if count > 0 { ... }.
This can feel strict at first. In practice, it is a safety net that catches bugs where an unexpected number or empty value silently passes as true.
You can chain else if when there are more than two conditions, for instance if the order qualifies for one of three shipping rates.
2. Three Kinds of Loops: loop, while, and for
You cannot copy and paste the same code ten or a hundred times. Loops let you repeat similar work cleanly.
Rust gives you three loop constructs so you can pick the one that fits best: loop, while, and for.
loop repeats unconditionally until it hits a break command, while repeats as long as a condition stays true, and for walks through a range or collection one item at a time. Let's compare all three side by side in a single program.
fn main() {
// for: include the last receipt number, 3
for receipt_no in 1..=3 {
println!("Receipt {}", receipt_no);
}
// while: repeat while the condition is true
let mut n = 3;
while n > 0 {
println!("Countdown {}", n);
n -= 1;
}
// loop: double the capacity until it can hold 16 items
let mut capacity = 1;
let box_size = loop {
capacity *= 2;
if capacity >= 16 {
break capacity;
}
};
println!("Box capacity: {} items", box_size);
}Output:
Receipt 1
Receipt 2
Receipt 3
Countdown 3
Countdown 2
Countdown 1
Box capacity: 16 itemsfor receipt_no in 1..=3 sets receipt_no to 1, 2, and 3 in order. The receipt numbers in the output follow the same sequence. ..= includes the end of the range.
Without the equals sign, 1..3 stops before 3. That is why 1..=3 and 1..4 visit the same three numbers.
Name the value for its job, such as receipt_no. One name to watch out for is gen: the Rust 2024 edition reserves it.2
Next is the while loop. We declare a mutable variable with let mut n = 3; and keep running as long as n > 0 is true.
Each pass subtracts 1 with n -= 1;, printing 3, 2, and 1 until n hits 0 and the loop ends.
A common beginner mistake with while is forgetting the line that updates the condition (n -= 1;). When that happens, n > 0 stays true forever and your program gets stuck in an infinite loop.
Always make sure the loop updates state so the condition will eventually become false.
A loop has no condition at the top, so its body decides when to stop. You can return the chosen capacity from it with break capacity;.
The value after break becomes the value of the loop expression and goes into box_size.
The capacity starts at 1 and doubles with capacity *= 2;. It reaches 2, 4, 8, then 16. At that point capacity >= 16 is true, so break capacity; hands the number back and exits the loop.
A for loop can take each item directly from a collection, so you do not have to calculate an index yourself.
Remember that 0..5 runs five times (0, 1, 2, 3, 4) while 0..=5 runs six times through 5. Reach for while when you want to keep going until a condition changes, and use loop when you want to return a result directly via break.
3. Writing Functions and Return Values
As your program grows, it helps to group reusable logic under a single name and call it whenever you need it. That named block of code is a function.
In Rust, you define a function using the form fn name(parameter: Type) -> ReturnType { ... }.
The parameters in parentheses are the inputs the function receives, and the type after the arrow (->) is the output it returns.
Rust can infer the types of local variables, but you write the parameter types in the function's signature. A function that returns a value like the one below declares its type after ->. With no return type written, as in fn main(), it returns ().
Change the quantity on an order form and it calculates a new total. Here main reads that quantity from the terminal, and order_total does the multiplication. Each item costs 1200 won.
Replace src/main.rs with this program and run cargo run --quiet. Type 3 at the prompt and press Enter.
fn order_total(quantity: u32, unit_price: u32) -> u32 {
quantity * unit_price
}
fn main() {
println!("Enter the order quantity:");
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("could not read the input");
let quantity: u32 = input.trim().parse().expect("enter a nonnegative integer");
if quantity == 0 || quantity > 100 {
println!("Enter a quantity from 1 to 100.");
return;
}
let total = order_total(quantity, 1200);
println!("{} items, total: {} won", quantity, total);
}The middle line is the number you typed. The program prints the prompt and the total on either side of it.
Enter the order quantity:
3
3 items, total: 3600 wonWhat you type arrives as text. String::new() makes an empty string named input; std::io::stdin() gives the program access to standard input, and read_line(&mut input) adds one line to the string. The :: in String::new() calls a function attached to the type. You also see it separating parts of a path such as std::io.3
trim() discards the trailing newline from Enter and any surrounding whitespace. parse() reads the remaining text as a number, using the : u32 on quantity to choose the integer type.
If reading fails or you type text such as abc, this first version stops with the message passed to expect(...). Even when parsing succeeds, main prints a message and exits before calculating a total if the count is outside 1 through 100. In Part 7 we'll handle bad input as a value instead.
Call order_total(quantity, 1200) with a quantity of 3 and its parameters get 3 and 1200. The function returns 3600 because multiplication is the final expression. Add a semicolon to make it quantity * unit_price; and the block yields (), which conflicts with its declared return type u32.4
The &mut in read_line(&mut input) gives the function permission to modify the string. Part 4 explains who owns that string, and Part 5 explains how another function can borrow it.
Footnotes
- The Rust Programming Language, Ch. 3.5 Control Flow. https://doc.rust-lang.org/book/ch03-05-control-flow.html β©
- The Rust Edition Guide (Rust 2024), The gen keyword: https://doc.rust-lang.org/edition-guide/rust-2024/gen-keyword.html β©
- Rust Standard Library, std::io::Stdin::readline: [https://doc.rust-lang.org/std/io/struct.Stdin.html#method.readline](https://doc.rust-lang.org/std/io/struct.Stdin.html#method.read_line) β©
- The Rust Programming Language, Ch. 3.3 Functions: https://doc.rust-lang.org/book/ch03-03-functions.html β©