So far, every calculation the cashier makes is written right inside main, like sweet_price * portions. Once there are ten orders, the same formula gets written ten times. Functions solve that problem. A function is a named recipe: it takes ingredients (parameters), works on them, then hands over its result (the return value, the value given back). In Rust, the type of every ingredient and the type of the result must be written.
The counting card at the till of Rusdi's Pancake Stall is a recipe too: "give me a price and a number of portions, and I hand back the total". Its ingredient boxes are labelled: the price must be a whole number, and so must the portions. The result is handed over on a plate on the recipe's last line. If that plate gets covered by a semicolon, all that reaches the cashier is an empty tray. In this picture, the counting card is the function, the ingredient boxes are the parameters, and their labels are the parameter types. The plate on the last line is the function's result, and the empty tray is (), the empty value.
Making and calling a function
This code makes the function total_price, then calls it from main:
fn total_price(price: u32, portions: u32) -> u32 {
price * portions
}
fn main() {
let total = total_price(38, 2);
println!("Total: {}", total);
}
The output:
Total: 76
fn total_price(...)makes a function. Its name is snake_case, like a variable. A function may be written above or belowmain.price: u32, portions: u32are the parameters. Every parameter must have a type. Rust doesn't guess parameter types.-> u32is the return type, the type of the function's result: this function hands over au32.- The code between the curly braces is called the function's body.
price * portionson its last line, without a semicolon, is the value returned. total_price(38, 2)calls the function. The values sent in, 38 and 2, are called arguments. Arguments are filled in by position: 38 goes intoprice, 2 intoportions. The result, 76, is stored intotal.
Expressions and statements
Rust tells two kinds of line apart:
- An expression produces a value:
38,price * portions,total_price(38, 2). - A statement is a command ending in
;. It hands over no real value: only(), the empty value, whose type is also written().
A semicolon turns an expression into a statement. Try putting a semicolon on the last line of total_price, so it reads price * portions;. Before you look at the result, guess: does the program still print Total: 76? This is the compiler's answer:
error[E0308]: mismatched types
--> src/main.rs:1:46
|
1 | fn total_price(price: u32, portions: u32) -> u32 {
| ----------- ^^^ expected `u32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | price * portions;
| - help: remove this semicolon to return this value
-> u32says this function hands over au32. But because of the semicolon, its body has no expression at the end, so the function quietly hands over()(that is what the lineimplicitly returns ...says).help:points at the semicolon to delete. The compile fails, so nothing prints at all.
return, and functions with no result
This code uses return and adds a second function that only prints:
fn total_price(price: u32, portions: u32) -> u32 {
return price * portions;
}
fn print_receipt(menu: &str, total: u32) {
println!("{}: {}", menu, total);
}
fn main() {
print_receipt("Egg Pancake x2", total_price(38, 2));
}
The output:
Egg Pancake x2: 76
returnhands over a value and leaves the function right away. Withreturn, a semicolon is fine. The Rust habit: the last line needs neitherreturnnor a semicolon, andreturnis for leaving early.print_receipthas no->. A function with no return type hands over(): its only job is to print.menu: &strmeans a parameter whose type is text.- In
main, the result oftotal_price(38, 2)becomes the second argument ofprint_receipt.
Choosing the result with if
A function often has to choose its result. The details of if come in the next lesson. For now, this is the pattern to know:
fn menu_price(menu: &str) -> u32 {
if menu == "sweet" {
32
} else if menu == "egg" {
38
} else if menu == "iced tea" {
5
} else {
0
}
}
fn main() {
println!("{}", menu_price("egg"));
println!("{}", menu_price("meatballs"));
}
The output:
38
0
menu == "sweet"compares text, and the result istrueorfalse. Two equals signs compare, one fills a variable.- Each
{ }block afterif,else iforelseis one branch. Only one branch is chosen, and the value in that branch, without a semicolon, becomes the function's result. - The last
elsecatches every unknown menu item, so"meatballs"gets0. - In the exercise, the function hands over an
f64. A whole-numberf64prints without.0: a result of13.0prints as13.
⚠️ The errors you will see most while writing functions
- A semicolon on the last line.
expected `u32`, found `()`means the result is covered by a semicolon. Delete the semicolon. - A parameter with no type.
fn total_price(price, portions: u32)is refused withexpected one of `:`, `@`, or `|`, found `,`. Writeprice: u32. - Forgetting
->. If the function body produces a number but there is no->, the compiler writesexpected `()`, found `u32`and suggests-> u32. - Wrong arguments.
total_price(38)is refused withthis function takes 2 arguments but 1 argument was supplied(it needs 2, it got 1), andtotal_price(38, 2.5)withexpected `u32`, found floating-point number.
TL;DR: A function is named code that takes values (parameters) and hands over a result. It is written fn name(param: Type, ...) -> ResultType { ... }. Every parameter must have a type, and -> writes the type of the result. A function's result is its last expression (code that produces a value) without a semicolon: price * portions. A semicolon turns it into a statement that hands over (), the empty value. The compiler then refuses with expected `u32`, found `()` plus a suggestion to delete the semicolon. return leaves the function early, and a function with no -> hands over (). To choose a result, use if ... else if ... else, with a value and no semicolon in each branch.
⚡ A named recipe
Write:
fn total_price(price: u32, portions: u32) -> u32 {
price * portions
}
let total = total_price(38, 2); // 76
Meaning: fn makes a function, named code that takes values and hands over a result. price: u32, portions: u32 are the parameters (the values the function takes), and every parameter must have a type. -> u32 writes the type of the result. When the function is called, the arguments (the values sent in) are filled in by position: 38 goes into price, 2 into portions. The result is price * portions, which is 76.
⚡ The result has no semicolon
Guess first: in the function from the previous step, the last line gets a semicolon, so it reads price * portions;. Does total still hold 76?
No. The semicolon makes the function hand over (), the empty value, although its result type is u32. The compiler refuses with expected `u32`, found `()` , and help: points at the semicolon to delete.
Meaning: An expression is code that produces a value, such as price * portions. A function's result is the expression on its last line without a semicolon, no return needed. A semicolon turns it into a statement, a command that hands over (). return is for leaving the function early.
⚡ Choosing the result with if
Write:
fn menu_price(menu: &str) -> u32 {
if menu == "sweet" {
32
} else if menu == "egg" {
38
} else {
0
}
}
Meaning: menu == "sweet" compares text. Each { } block after if, else if or else is one branch. Only one branch is chosen, and its value, without a semicolon, becomes the function's result. The last else catches every unknown menu item.