In Rust, blocks, if and even loop produce values. This part covers functions, return values, the semicolon that breaks them, if as a value, loop with break, while, for over ranges and labelled loops.
In Rust, almost everything produces a value. A block does, an if does, and even a loop does. That one fact explains why a function’s last line has no return, why one extra semicolon can break a function, and how a loop can hand back a result.
This part covers functions and their types, statements and expressions, if, loop, while, for and labelled loops. It builds on the variables and types from Part 2. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
This function should square a number. Decide what the program prints before you scroll down:
fn square(x: i32) -> i32 {
x * x;
}
fn main() {
println!("{}", square(4));
}
It doesn’t print 16. It doesn’t compile:
error[E0308]: mismatched types
--> src/main.rs:1:22
|
1 | fn square(x: i32) -> i32 {
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | x * x;
| - help: remove this semicolon to return this value
The whole problem is the ; after x * x. The compiler even says so on the last line: help: remove this semicolon to return this value. Remove it, and the program prints 16.
Read the error from the top. The function promises to return an i32. The body actually gives back (), which is Rust’s “no value”. The middle line says why: the body has no “tail”, no last expression without a semicolon. By the end of this part, every word of that error will make sense.
Functions
Here are two small functions, one that returns a value and one that doesn’t:
fn main() {
let total = add(2, 3);
println!("2 + 3 = {total}");
greet("Ana");
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn greet(name: &str) {
println!("hello, {name}");
}
It prints:
2 + 3 = 5
hello, Ana
The pieces of a function are:
fn, then the name insnake_case;- the parameters in brackets, each one
name: Type; -> Typefor the type it returns;- the body, in
{ }.
&str is the type of a piece of text like "Ana". Part 5 covers strings properly; for now, read &str as “some text”.
Notice that main calls add before add is defined. That’s fine. Rust doesn’t care about the order of functions in a file.
greet has no ->. A function without one returns (), the unit type. It’s an empty value that means “nothing useful came back”. println! is the same: it does its work and returns ().
Parameters always need types
Inside a function, Rust works out most types for you. In Part 2, let x = 5 didn’t need : i32. A function’s signature is different. Every parameter needs its type written out:
fn add(a, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(1, 2));
}
It prints:
error: expected one of `:`, `@`, or `|`, found `,`
--> src/main.rs:1:9
|
1 | fn add(a, b: i32) -> i32 {
| ^ expected one of `:`, `@`, or `|`
...
help: if this is a parameter name, give it a type
This is a rule, not a gap in the compiler. The signature is a contract between the function and everyone who calls it. Rust checks each function’s body against its own signature, and each call against that same signature. So when something is wrong, the error points at the function or at the call, not at some line far away where a guessed type finally stopped fitting.
Statements and expressions
Rust code is made of two kinds of things:
- An expression produces a value.
5,a + b,add(2, 3)andx > 0are all expressions. - A statement does something and produces no value.
let total = 5;is a statement. So is any expression with a;after it: the semicolon runs the expression and throws its value away.
A block, the code between { and }, is an expression too. Its value is its last expression, as long as that expression has no semicolon after it. That last expression is called the tail.
fn main() {
let width = 4;
let area = {
let height = 3;
width * height
};
println!("area = {area}");
}
It prints:
area = 12
The block runs let height = 3;, a statement. Then its tail, width * height, gives the whole block its value, 12, and let area stores it. height only exists inside the block. After the }, it’s gone.
A function body is a block, so the same rule applies. The tail of the body is the value the function returns. That’s why add ends with a + b and no return.
Now look at the Try this first program again. In x * x;, the semicolon turned the tail into a statement. The body had no tail left, so its value was (). The signature promised an i32, and () isn’t an i32. That’s the “mismatched types”.
return for early exit
You can still write return. Use it when a function needs to stop before its last line:
fn ticket_price(age: u32) -> u32 {
if age < 5 {
return 0;
}
if age >= 65 {
return 6;
}
12
}
fn main() {
for age in [3, 30, 70] {
println!("age {age}: {} euros", ticket_price(age));
}
}
It prints:
age 3: 0 euros
age 30: 12 euros
age 70: 6 euros
The two returns handle the special cases and leave the function at once. The normal case is the tail, 12. Writing return 12; on the last line would also work, but clippy, Rust’s linter, warns about it: “unneeded return statement”. Rust programmers keep return for leaving early.
The [3, 30, 70] is an array. Part 4 covers arrays; here we only loop over it.
if is an expression
In many languages, if only chooses which code to run. In Rust, if also has a value: the value of the block that ran. So you can put an if on the right of a let:
fn main() {
let temp = 22;
let label = if temp > 30 {
"hot"
} else if temp > 15 {
"mild"
} else {
"cold"
};
println!("{temp} degrees is {label}");
}
It prints:
22 degrees is mild
This is why Rust has no ? : operator. if temp > 30 { "hot" } else { "cold" } already does that job.
Two rules come with it. The condition must be a bool. Rust doesn’t treat 0 as false or a non-zero number as true. And every arm must give the same type, because label can only have one type:
fn main() {
let score = 72;
let grade = if score >= 50 { "pass" } else { 0 };
println!("{grade}");
}
It prints:
error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:3:50
|
3 | let grade = if score >= 50 { "pass" } else { 0 };
| ------ ^ expected `&str`, found integer
| |
| expected because of this
The first arm decided the type: text, a &str. The second arm gave an integer, so the compiler points at the 0 and at the arm that set the type.
loop, and breaking out with a value
loop runs its body again and again, forever, until something stops it. break stops it. And break can carry a value out of the loop, which then becomes the value of the whole loop expression:
fn main() {
let mut counter = 1;
let result = loop {
counter *= 2;
if counter > 10 {
break counter;
}
};
println!("result = {result}");
}
It prints:
result = 16
The animation runs this loop one pass at a time. The code is on the left, and the two variables are on the right.
Each pass doubles counter and checks it. The pass that finds 16 runs break counter, and the 16 becomes the value of the whole loop, which let result stores.
Here are those steps in words, in case the animation doesn’t play for you:
let mut counter = 1setscounterto 1.resultdoesn’t have a value yet, because the loop hasn’t produced one.- Pass 1:
counter *= 2makes it 2.2 > 10is false, so the loop goes round again. - Pass 2:
counterbecomes 4.4 > 10is false, so it goes round again. - Pass 3:
counterbecomes 8.8 > 10is false, so it goes round again. - Pass 4:
counterbecomes 16.16 > 10is true, sobreak counterruns. It ends the loop and takes the value 16 with it. - The whole
loop { ... }expression now has the value 16, andlet resultstores it.
Notice the ; after the loop’s closing }. let result = loop { ... }; is a let statement, and every let ends with a semicolon.
Only loop can break with a value. A while or for loop can end because its condition became false or it ran out of items. Then no break ran, and there would be no value to give. A loop can only end through a break, so Rust knows a value always comes out. The second worked example below shows the error you get if you try it with while.
while
while checks a condition before each pass, and stops when it’s false. This one adds up the digits of a number:
fn main() {
let mut n = 4096;
let mut sum = 0;
while n > 0 {
sum += n % 10;
n /= 10;
}
println!("digit sum = {sum}");
}
It prints:
digit sum = 19
n % 10 is the last digit and n /= 10 drops it. The digits are 4, 0, 9 and 6, so the sum is 19. When n reaches 0, the condition is false and the loop ends.
for over ranges
To count, use for with a range. 0..5 is the numbers from 0 up to 5, not including 5. 0..=5 includes the 5. Add .rev() to go backwards:
fn main() {
for i in 0..5 {
print!("{i} ");
}
println!("(stops before 5)");
for i in 0..=5 {
print!("{i} ");
}
println!("(includes 5)");
for i in (1..=3).rev() {
print!("{i}... ");
}
println!("go!");
}
It prints:
0 1 2 3 4 (stops before 5)
0 1 2 3 4 5 (includes 5)
3... 2... 1... go!
print! is println! without the line break at the end. The brackets in (1..=3).rev() matter. Without them, Rust reads 3.rev() first, and an integer has no rev.
Because 0..n leaves out its end, it runs exactly n times. That’s usually what you want when you count.
continue skips the rest of the current pass and goes on to the next one:
fn main() {
for n in 1..=10 {
if n % 3 != 0 {
continue;
}
println!("{n} is a multiple of 3");
}
}
It prints:
3 is a multiple of 3
6 is a multiple of 3
9 is a multiple of 3
Prefer for over a while with a counter you update by hand. With for, you can’t forget the i += 1, and you can’t go one step too far.
Labelled loops
break and continue act on the innermost loop. To act on an outer one, give it a label: a name that starts with an apostrophe, like 'outer. Here we look for two numbers from 1 to 9 that add up to 10 and multiply to 21:
fn main() {
let mut checked = 0;
'outer: for a in 1..10 {
for b in a..10 {
checked += 1;
if a + b == 10 && a * b == 21 {
println!("found {a} and {b}");
break 'outer;
}
}
}
println!("checked {checked} pairs");
}
It prints:
found 3 and 7
checked 22 pairs
A plain break would only leave the inner loop over b. The outer loop would carry on with a = 4, and keep checking pairs after we already have our answer. break 'outer leaves both loops at once. continue 'outer works the same way: it jumps straight to the next a.
The apostrophe looks like the lifetimes you’ll meet in Part 9, such as 'a. They’re not related. A loop label is just a name for a loop.
A labelled loop can also break with a value: break 'outer value;. As with a plain break, that only works when the loop being left is a loop, not a for or while.
Worked example: counting steps with loop
The Collatz rule takes a number and halves it if it’s even, or triples it and adds 1 if it’s odd. Repeat, and every number anyone has tried ends up at 1. How many steps does it take? This function puts several pieces of this part together:
fn collatz_steps(mut n: u64) -> u32 {
let mut steps = 0;
loop {
if n == 1 {
break steps;
}
n = if n % 2 == 1 { 3 * n + 1 } else { n / 2 };
steps += 1;
}
}
fn main() {
for start in [1, 6, 7, 27] {
println!("{start}: {} steps", collatz_steps(start));
}
}
It prints:
1: 0 steps
6: 8 steps
7: 16 steps
27: 111 steps
Look at it piece by piece:
mut nin the parameter list makes the parameter a variable we can change inside the function. The caller’s number isn’t affected:ngets its own copy.- The
loopis the tail of the function body. It has no semicolon after it, so its value is what the function returns. break stepsends the loop and hands backsteps, au32, which matches-> u32.n = if ... { 3 * n + 1 } else { n / 2 };usesifas a value. Both arms areu64, the type ofn. We test for odd withn % 2 == 1. If you test for even withn % 2 == 0on an unsigned number, clippy suggestsn.is_multiple_of(2)instead, which says the same thing in words.
A loop with a break is the natural shape when you don’t know how many passes you need, and the answer comes from the pass that stops.
Worked example: break with a value from while
You want the first multiple of 7 above 50. The first try uses while, because “go up until you find it” sounds like a while:
fn main() {
let mut n = 50;
let found = while n < 100 {
n += 1;
if n % 7 == 0 {
break n;
}
};
println!("{found}");
}
It prints:
error[E0571]: `break` with value from a `while` loop
--> src/main.rs:6:13
|
3 | let found = while n < 100 {
| ------------- you can't `break` with a value in a `while` loop
...
6 | break n;
| ^^^^^^^ can only break with a value inside `loop` or breakable block
...
error[E0277]: `()` doesn't implement `std::fmt::Display`
--> src/main.rs:9:15
|
9 | println!("{found}");
| ^^^^^^^ `()` cannot be formatted with the default formatter
There are two errors. Start with the first one, because the second is often caused by it.
The first line names the problem: a break with a value, inside a while. The dashes under while n < 100 say which loop. The carets under break n; say which break. The rule is the one from earlier: a while can end because n < 100 became false, and then no value would come out.
The second error follows from the first. A while loop’s value is always (), so found is (), and println! can’t print () with {}. Fix the first error and the second one goes away.
The fix is to say what you mean. “Keep going until you find it” is a loop:
fn main() {
let mut n = 50;
let found = loop {
n += 1;
if n % 7 == 0 {
break n;
}
};
println!("{found}");
}
It prints:
56
The n < 100 limit is gone, because a multiple of 7 always turns up within seven steps. If your search might find nothing, keep the while and use a plain break, or return early from a function. Part 11 shows Option, Rust’s way to say “maybe a value”.
Tips and traps
- A semicolon on the last line of a function. The error is E0308 “mismatched types”, with
expected i32, found ()andhelp: remove this semicolon to return this value. Remove it, so the last expression becomes the tail again. - An
ifused as a value, with noelse.let x = if n > 5 { "big" };fails with E0317, “ifmay be missing anelseclause”. Whennis 5 or less, there’d be no value. Add anelsearm of the same type. - A number as a condition.
if count { ... }with an integercountfails with E0308, “expectedbool, found integer”. Write the comparison you mean:if count != 0. 0..5stops at 4. If the last value is missing from your output, you wanted0..=5.1..=3.rev()without brackets. Rust tries to callrevon3, and fails with E0689, “can’t call methodrevon type{integer}“. Write(1..=3).rev().break valuein awhileorfor. That’s E0571. Turn the loop into aloop, as in the worked example.- A
loopwith nobreakruns forever. If your program hangs, check that every path through the loop can reach abreak, or areturn.
In Rust, a block is worth its last expression, and a semicolon after it throws that value away.
Exercises
Exercise 1. Without running it, decide what this prints:
let x = {
let a = 2;
a * a + 1
};
let y = if x % 2 == 0 { x / 2 } else { 3 * x + 1 };
println!("{x} {y}");
Exercise 2. Write fn sum_to(n: u32) -> u32 that adds the numbers from 1 to n, using a for loop over a range and no return. sum_to(4) should be 10 and sum_to(100) should be 5050.
Exercise 3. Use a loop that breaks with a value to find the smallest power of 3 that is larger than 500. Print it.
Answers
1. The block’s tail is a * a + 1, so x is 5. 5 is odd, so the else arm runs and y is 3 * 5 + 1, which is 16:
fn main() {
let x = {
let a = 2;
a * a + 1
};
let y = if x % 2 == 0 { x / 2 } else { 3 * x + 1 };
println!("{x} {y}");
}
It prints:
5 16
2. Use 1..=n so that n itself is included, and make total the tail of the function:
fn sum_to(n: u32) -> u32 {
let mut total = 0;
for i in 1..=n {
total += i;
}
total
}
fn main() {
println!("{}", sum_to(4));
println!("{}", sum_to(100));
}
It prints:
10
5050
With 1..n, you’d get 6 and 4950, because the range would stop one short.
3. Start at 1, multiply by 3 on each pass, and break with the value as soon as it’s past 500:
fn main() {
let mut power = 1;
let answer = loop {
power *= 3;
if power > 500 {
break power;
}
};
println!("{answer}");
}
It prints:
729
The powers go 3, 9, 27, 81, 243, 729. 243 is too small, so 729 is the first one past 500.
What’s next
So far, every value has been a single number or a piece of text. In Part 4, we’ll group values together with tuples and arrays, and take a first look at slices, a view into part of an array.