Part 01 · Rust Is Not Scary
Functions
Writing functions, and the one Rust habit that surprises everyone: the last line without a semicolon is the return value.
⏱ 9 min · Station 7 of 75
The story
A sugarcane juice machine on the street has one job. You put cane in one side, it hands juice out the other. You don't need to know how the rollers work inside; you only need to know what goes in and what comes out.
A function is that machine for code. You give it some values (its inputs, called parameters), it does one job, and it hands one value back (its return value). Our shop needs machines like "price times quantity" and "turn paisa into a taka string". Rust functions have one habit that surprises everyone in the first week: the value that comes out is simply the last line, without a semicolon.
The idea
fn line_total(price_paisa: u64, quantity: u64) -> u64 {
price_paisa * quantity
}
Read it left to right:
fn line_total: a function namedline_total. Function names usesnake_case, lower case with underscores.(price_paisa: u64, quantity: u64): two parameters, and each one must have a type. Rust never guesses types at the edge of a function; the function's signature is a promise to everyone who calls it.-> u64: the function hands back au64. No arrow means it returns nothing.price_paisa * quantity: the last line, without;. That is the return value.
That last point is the habit. In Rust, almost everything is an expression: a piece of code that produces a value. price_paisa * quantity is an expression. Adding a ; turns it into a statement: "do this and throw the result away". The function returns the value of its last expression, so the last line must not end in ;.
Try it: the shop's first functions
Three small functions: one calculates, one formats, one prints:
fn line_total(price_paisa: u64, quantity: u64) -> u64 {
price_paisa * quantity
}
fn taka(paisa: u64) -> String {
format!("{}.{:02}", paisa / 100, paisa % 100)
}
fn print_line(name: &str, paisa: u64) {
println!("{name:<12}{:>10}", taka(paisa));
}
fn main() {
let rice = line_total(8_400, 5); // 5 kg at ৳84.00
let eggs = line_total(1_250, 12); // 12 eggs at ৳12.50
print_line("Rice 5kg", rice);
print_line("Eggs x12", eggs);
print_line("Total", rice + eggs);
}
Rice 5kg 420.00
Eggs x12 150.00
Total 570.00
line_totalreturns au64, so it ends with an expression and no;.takareturns aString.format!builds text the same wayprintln!prints it, and since it's the last line without;, that text is returned.print_linehas no->, so it returns nothing. Its last line does end with;. (Itsname: &strparameter means "some text"; you'll learn exactly what&stris in String vs &str.)maincalls them, and their results flow into the next call:print_line("Total", rice + eggs).
Blocks { ... } follow the same rule as functions. The last expression without ; is the block's value:
fn main() {
let price = 8_400;
let total = {
let quantity = 5;
price * quantity // no semicolon: this is the block's value
};
println!("total: {total}");
let nothing = {
price * 5; // semicolon: the value is thrown away
};
println!("nothing: {nothing:?}");
}
The second block ends with price * 5; (with a semicolon). What is nothing?
warning: unused arithmetic operation that must be used
--> src/main.rs:10:9
|
10 | price * 5; // semicolon: the value is thrown away
| ^^^^^^^^^ the arithmetic operation produces a value
|
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
|
10 | let _ = price * 5; // semicolon: the value is thrown away
| +++++++
total: 42000
nothing: ()
() is called unit: Rust's "nothing here" value. A function with no -> really returns (). And notice the warning above the output: the compiler noticed you calculated price * 5 and then threw it away, which is almost always a mistake.
What the compiler says
Now the classic first-week mistake: the semicolon on the last line of a function that promised to return something.
fn line_total(price_paisa: u64, quantity: u64) -> u64 {
price_paisa * quantity;
}
fn main() {
println!("{}", line_total(8_400, 5));
}
error[E0308]: mismatched types
--> src/main.rs:1:51
|
1 | fn line_total(price_paisa: u64, quantity: u64) -> u64 {
| ---------- ^^^ expected `u64`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | price_paisa * quantity;
| - help: remove this semicolon to return this value
For more information about this error, try `rustc --explain E0308`.
error: could not compile `semi` (bin "semi") due to 1 previous error
Read it with the machine picture in mind:
error[E0308]: mismatched types: same error ID as in Why Rust Feels Hard: you gave one type where another was needed.expected `u64`, found `()`: the-> u64promised a number, but the body produced(), nothing.implicitly returns `()` as its body has no tail or `return` expression: the tail is that last expression without;. There isn't one, so the function returns().help: remove this semicolon to return this value: the compiler even points at the exact;. Delete it and it compiles.
Forgetting the parameter types is the other common one:
fn line_total(price_paisa, quantity) -> u64 {
price_paisa * quantity
}
fn main() {
println!("{}", line_total(8_400, 5));
}
error: expected one of `:`, `@`, or `|`, found `,`
--> src/main.rs:1:26
|
1 | fn line_total(price_paisa, quantity) -> u64 {
| ^ expected one of `:`, `@`, or `|`
|
help: if this is a parameter name, give it a type
|
1 | fn line_total(price_paisa: TypeName, quantity) -> u64 {
| ++++++++++
help: if this is a type, explicitly ignore the parameter name
|
1 | fn line_total(_: price_paisa, quantity) -> u64 {
| ++
error: expected one of `:`, `@`, or `|`, found `)`
--> src/main.rs:1:36
|
1 | fn line_total(price_paisa, quantity) -> u64 {
| ^ expected one of `:`, `@`, or `|`
|
help: if this is a parameter name, give it a type
|
1 | fn line_total(price_paisa, quantity: TypeName) -> u64 {
| ++++++++++
help: if this is a type, explicitly ignore the parameter name
|
1 | fn line_total(price_paisa, _: quantity) -> u64 {
| ++
error: could not compile `notype` (bin "notype") due to 2 previous errors
Two errors, one per parameter, and the first help: line is the one you want: give it a type, as in price_paisa: u64. (The second suggestion, _: price_paisa, is for a different situation; ignore it.)
Under the hood
return exists too. return value; leaves the function immediately. Rust code uses it for early exits, like "if the cart is empty, return 0 right away", and lets the last expression do the normal return. Writing return x; on the last line works, but it isn't the usual Rust style.
Why are parameter types required? Because the signature is a contract. Rust works out types inside a function from how values are used, but the edges must be written down, so that a change inside one function can never silently change what its callers receive. It also makes error messages point at the right place: "you passed a f64 where line_total wants a u64", not an error twenty lines deep.
Calling a function is cheap. Arguments are passed in CPU registers when they fit, and in release builds small functions like line_total are usually inlined: the compiler pastes the body into the caller, so there's no call at all. Splitting code into many small functions costs you nothing at runtime, so do it whenever it makes the code clearer.
Order doesn't matter. main can call line_total even if line_total is written below it. The compiler reads the whole file first.
Compared with other languages
Forgetting to return a value is a real bug in other languages too. Python doesn't notice:
def line_total(price_paisa, quantity):
price_paisa * quantity # forgot `return`
rice = line_total(8400, 5)
print("rice:", rice)
print("with eggs:", rice + 15000)
rice: None
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Python functions without return give back None. So line_total "worked", rice quietly became None, and the crash came later, on a different line, when someone tried to use it. In a real codebase that other line could be in another file, written by someone else, running weeks later. (JavaScript behaves the same way with undefined.)
Go catches it at compile time, like Rust:
package main
import "fmt"
func lineTotal(pricePaisa, quantity uint64) uint64 {
pricePaisa * quantity // forgot `return`
}
func main() {
fmt.Println(lineTotal(8400, 5))
}
# command-line-arguments
./main.go:6:2: pricePaisa * quantity (value of type uint64) is not used
./main.go:7:1: missing return
| Python | JavaScript | Go | Rust | |
|---|---|---|---|---|
| Parameter types | optional hints | none (TypeScript adds them) | required | required |
| Return value | return x | return x | return x | last expression, or return x |
| Forgot to return | None, fails later | undefined, fails later | compile error | compile error with "remove this semicolon" |
Key takeaway
A function is a machine: typed parameters go in, one value comes out. Every parameter needs a type and -> says what comes back. The return value is the last expression without a semicolon; adding ; turns it into a statement that returns (), and the compiler's E0308 will point at that exact semicolon. Use return for early exits. Small functions are free, so use them to give names to every idea in your code.
Practice
Objective: write small functions that take parameters and return values.
Challenge: three friends split a bill of ৳1250.50. Write share(total_paisa, people) -> u64 for what each person pays, leftover(total_paisa, people) -> u64 for the paisa that don't divide evenly, and reuse taka(paisa) -> String. Print each share, the leftover, and a check line that adds it all back up.
Expected result:
each pays 416.83 taka
1 paisa left over
check: 41683 x 3 + 1 = 125050
Hint 1
Whole-number division / gives the share; % gives what's left over.
Hint 2
Each function body is a single expression with no ;, e.g. total_paisa / people.
Hint 3
The check is each * people + left, which must equal the bill exactly. That's the reason to work in paisa.
Solution
fn share(total_paisa: u64, people: u64) -> u64 {
total_paisa / people
}
fn leftover(total_paisa: u64, people: u64) -> u64 {
total_paisa % people
}
fn taka(paisa: u64) -> String {
format!("{}.{:02}", paisa / 100, paisa % 100)
}
fn main() {
let bill = 125_050; // ৳1250.50
let people = 3;
let each = share(bill, people);
let left = leftover(bill, people);
println!("each pays {} taka", taka(each));
println!("{left} paisa left over");
println!("check: {} x {people} + {left} = {}", each, each * people + left);
}
That 1 leftover paisa matters: if every friend pays ৳416.83, the shop is a paisa short. You'll handle it properly (one person pays the extra paisa) when you build the bill splitter at the end of this part.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →