You write a two-line function, double(). It promises an i32 and multiplies its argument by two. The compiler refuses it with error[E0308]: mismatched types: expected i32, found ().
The bug is one semicolon. By the end of this lesson you'll see it before the compiler does, and you'll be able to say what that one character changed.
This lesson covers functions with typed parameters and a return type, the difference between an expression and a statement, building text with format!, the three loops (for, while and loop), ranges, and range patterns in match. It uses match only for range patterns; Lesson 6 teaches match in full, including exhaustiveness. It assumes Lesson 2's let, mut and number types.
Take a look at Example 1.
Example 1. One semicolon too many (examples/compile-fail/f03_semicolon.rs)
fn double(n: i32) -> i32 {
n * 2;
}
fn main() {
println!("{}", double(4));
}
Before you compile it, predict the problem. Then, from the examples folder, hand it to the compiler:
rustc --edition=2024 compile-fail/f03_semicolon.rs
error[E0308]: mismatched types
--> compile-fail/f03_semicolon.rs:1:22
|
1 | fn double(n: i32) -> i32 {
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | n * 2;
| - help: remove this semicolon to return this value
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0308`.We'll take that message apart after a function that works.
Where is the return?
In PHP you'd write function shippingCents(int $weightGrams): int. Rust writes the same promise in nearly the same place. Take a look at Example 2, a small shipping calculator.
Example 2. Functions, ranges and loops (examples/src/bin/b03_functions.rs)
// Lesson b03: functions, expressions and control flow.
fn shipping_cents(weight_grams: u32) -> u32 {
// The last expression, with no semicolon, is the return value.
if weight_grams <= 500 {
499
} else {
499 + ((weight_grams - 500) / 250) * 100
}
}
fn label(cents: u32) -> String {
format!("${}.{:02}", cents / 100, cents % 100)
}
fn main() {
for grams in [300, 500, 1000] {
println!("{grams} g -> {}", label(shipping_cents(grams)));
}
// Ranges: 1..4 stops before 4, 1..=3 includes 3.
let mut total = 0;
for n in 1..4 {
total += n;
}
println!("sum 1..4 = {total}");
println!("sum 1..=3 = {}", (1..=3).sum::<u32>());
// `while` repeats while a condition is true.
let mut countdown = 3;
while countdown > 0 {
println!("countdown {countdown}");
countdown -= 1;
}
// `loop` can hand a value back through `break`.
let mut tries = 0;
let first_over_ten = loop {
tries += 1;
if tries * tries > 10 {
break tries;
}
};
println!("first number whose square is over 10: {first_over_ten}");
}
Run it with cargo run --quiet --bin b03_functions:
300 g -> $4.99
500 g -> $4.99
1000 g -> $6.99
sum 1..4 = 6
sum 1..=3 = 6
countdown 3
countdown 2
countdown 1
first number whose square is over 10: 4Start with shipping_cents(weight_grams: u32) -> u32. It takes a weight and returns cents. Parameter types are required. The -> u32 is the return type; a function with no -> returns (), the empty value. The body is one if. Up to 500 grams it evaluates to 499, and above that it evaluates the arithmetic. In Rust, if is an expression: it produces a value. Here that value is the function's return value, so neither branch says return.¹
One character decides
The function double held the position that it returned an i32. Its signature said so, after the arrow. Its body was one line, n * 2;, which multiplied the argument by two and then, because of the character at the end, set the result down like a cup left on the counter instead of handed across. main asked for double(4). The compiler reported that double implicitly returns () as its body has no tail or return expression.
Here's the rule behind that. An expression produces a value. A statement performs an action and produces none. If a block ends with an expression and no semicolon, that expression is the block's value, and it has a name: the tail expression. In Example 1, n * 2; ends with a semicolon, which turns it into a statement. The body now ends with no value, so it returns (). The signature promised i32. That's error E0308, mismatched types, and the help line points at the character: remove this semicolon to return this value.
Delete the semicolon and n * 2 becomes the tail expression, so double(4) returns 8. return n * 2; also works. The rule is about the block's last line, not a ban on return.
Building text with format!
label() in Example 2 turns cents into text with format!. cents / 100 gives the dollars, cents % 100 gives the cents, and {:02} pads to two digits; the third output line, 1000 g -> $6.99, is label(699). format! returns a String. println! prints. One builds text; the other writes it out.
Three loops
The PHP version of Example 2, php/b03_functions.php, reaches for foreach, a counting for, while, and a while (true) with a break in the middle. Rust has three loops, and each says what kind of stopping it does. for walks over something. while checks a condition first. loop runs until you break.
The for loop in Example 2 walks a range. 1..4 yields 1, 2 and 3; the end is left out. 1..=3 includes its end. Both sum to 6, as the output shows. while countdown > 0 checks before each pass, prints, and subtracts one. The plain loop has no condition at all. break tries ends it and hands back tries, so first_over_ten becomes 4.
You could write the countdown as a loop with a break too, and that would be, depending on whether the stopping condition belongs at the top of the body or in the middle and whether you need a value back when it stops, either a fair way to say what you mean or a while written the long way round, and in first_over_ten the value comes back through break.
Can a match arm say "one to nine"?
Here's a PHP habit. You label stock levels with match (true), and each arm is a comparison. The order of the arms does the work, and the bands live in your head. Take a look at Example 3.
Example 3. Bands as comparisons in PHP (php/b03_match.php)
<?php
function stockLabel(int $quantity): string
{
return match (true) {
$quantity <= 0 => 'out of stock',
$quantity <= 9 => 'low stock',
default => 'in stock',
};
}
foreach ([-2, 0, 1, 9, 10, 250] as $quantity) {
echo $quantity . ' -> ' . stockLabel($quantity) . PHP_EOL;
}
Rust lets the arm say the band. Example 4 is the same function with range patterns.
Example 4. Bands as range patterns (examples/src/bin/b03_range_patterns.rs)
fn stock_label(quantity: i32) -> &'static str {
match quantity {
..=0 => "out of stock",
1..=9 => "low stock",
_ => "in stock",
}
}
fn main() {
for quantity in [-2, 0, 1, 9, 10, 250] {
println!("{quantity} -> {}", stock_label(quantity));
}
}
Run it with cargo run --quiet --bin b03_range_patterns, and run the PHP file with php php/b03_match.php. Both print the same six lines:
-2 -> out of stock
0 -> out of stock
1 -> low stock
9 -> low stock
10 -> in stock
250 -> in stockInside match quantity, the arm ..=0 covers zero and below, 1..=9 covers one to nine, and _ covers everything else. A range pattern is a pattern, a shape the matched value is compared to, with three parts: a lower bound, the .. or ..=, and an upper bound. Either bound can be left off, and it matches every value between them. Ranges in patterns only work for numbers and char. For now, read each arm as "if the value is in this band".
Does 9 match the pattern 1..9? No. 1..9 stops before 9, just like the loop range. Write 1..=9 when the end belongs in the band.
So the arms say the bands, and the Rust output matches the PHP output line for line. Now ask where the bands came from. Is 9 "low stock" because someone who runs the stockroom said so, or because 9 was the number that came to mind? When the threshold moves, which file changes, and who notices? Should the number live in the arm at all?
Testing
Predict before you check. Which integers does 1..4 produce? And what does double(4) return once the semicolon is gone? It's 1, 2 and 3, and 8.
Then, without the lesson open, write double() from memory, once with the bug and once without, and say what the semicolon changed. You can forget the semicolon rule. E0308 will remind you, and its help line points at the character.
TL;DR
A Rust function declares its parameter types and its return type, and a function with no -> returns (). if is an expression, so a function can end on one and return its value. A block's last expression, with no semicolon, is its value; add a semicolon and it becomes a statement, the block returns (), and a function that promised i32 fails with E0308. format! builds a String; println! prints. for walks a range or a collection, while checks first, and loop runs until break, which can hand back a value. 1..4 leaves out its end and 1..=3 includes it, in loops and in range patterns alike. Next: vectors and hash maps.
¹ The PHP version in php/b03_functions.php writes the same rule with return, a ternary and intdiv, and prints the same nine lines.