6 / 35

Rust Basics· 12 min read· Lesson 6 of 35

Functions

Part 1 · Rust. Write your own Rust functions with parameters and return values, and learn the difference between expressions and statements.

At Rusty Bean Café, every barista follows the same recipe for a latte. Nobody reinvents it for each customer: they just say “make a latte”. Functions are recipes for your code. You write the steps once, give them a name, and use that name whenever you need them. In this lesson you’ll write your own functions, pass information into them, and get answers back.

Your first function

You’ve already written one function, main. Let’s add another:

src/main.rs
fn main() {
println!("Opening the café...");
print_welcome();
print_welcome();
}
fn print_welcome() {
println!("Welcome to Rusty Bean Café!");
}
Output
Opening the café...
Welcome to Rusty Bean Café!
Welcome to Rusty Bean Café!
  1. fn print_welcome() { ... } defines a function: fn, then a name, then (), then a body in curly braces.
  2. Inside main, print_welcome(); calls the function. Rust jumps into its body, runs it, then comes back and carries on.
  3. We called it twice, so the welcome prints twice. We wrote the steps once and used them twice.

Function names use snake_case, like variables. Notice that print_welcome is defined after main. That’s fine: in Rust, a function can be defined anywhere in the file, before or after it’s used.

Parameters: passing information in

A recipe often needs details: “make a latte in size large”. Functions get details through parameters:

src/main.rs
fn main() {
greet_customer("Ada");
print_price("Latte", 450);
}
fn greet_customer(name: &str) {
println!("Hi {name}, what can we get you?");
}
fn print_price(item: &str, cents: u32) {
println!("{item}: {cents} cents");
}
Output
Hi Ada, what can we get you?
Latte: 450 cents
  1. greet_customer(name: &str) has one parameter called name, of type &str (text).
  2. When we call greet_customer("Ada"), the value "Ada" is passed in and becomes name inside the function. The value you pass in is called an argument.
  3. print_price has two parameters, separated by a comma. Arguments are matched up in order: "Latte" goes to item, 450 goes to cents.

Warning

In Rust, every parameter must have a type. Writing fn greet_customer(name) gives:

Output
error: expected one of `:`, `@`, or `|`, found `)`
--> src/main.rs:6:23
|
6 | fn greet_customer(name) {
| ^ expected one of `:`, `@`, or `|`
|
help: if this is a parameter name, give it a type

The help: line tells you the fix: add : TypeName, for example name: &str. Rust never guesses parameter types. That’s a deliberate choice: the function’s first line tells you exactly what it needs.

Return values: getting an answer back

Some recipes produce something you hand back, like a finished drink. A function can return a value. You write the return type after an arrow ->:

src/main.rs
fn main() {
let total = order_total(450, 2);
println!("Two lattes cost {total} cents");
}
fn order_total(price: u32, quantity: u32) -> u32 {
price * quantity
}
Output
Two lattes cost 900 cents
  1. -> u32 says “this function hands back a u32”.
  2. The body is just price * quantity, and there is no semicolon at the end. The last line of a function, without a semicolon, is the value it returns.
  3. In main, order_total(450, 2) runs the function and becomes 900, which we store in total.

Why no semicolon? To understand that, we need two words: expressions and statements.

Expressions vs. statements

  • An expression works something out and produces a value. 450 * 2 is an expression (it produces 900). So is order_total(450, 2), and so is a plain 450.
  • A statement does something but produces no value. let total = 900; is a statement. It stores a value, but the line itself isn’t a value you can use.

A useful analogy: an expression is a question with an answer (“What’s two lattes?” “900!”). A statement is an instruction (“Put 900 in the total jar.”).

Adding a semicolon turns an expression into a statement. The value is thrown away. So:

  • price * quantity → an expression, the value 900, which is returned.
  • price * quantity; → a statement, the value is thrown away and nothing is returned.

Blocks are expressions too

A block of code in curly braces produces the value of its last expression:

src/main.rs
fn main() {
let price_with_extra_shot = {
let base = 450;
let extra_shot = 75;
base + extra_shot
};
println!("Latte with extra shot: {price_with_extra_shot} cents");
}
Output
Latte with extra shot: 525 cents
  1. Inside the block, two let statements set things up.
  2. The last line, base + extra_shot, has no semicolon, so the whole block produces 525.
  3. That value is stored in price_with_extra_shot. Note the semicolon after the closing }. That one ends the let statement.

A function body is the same kind of block, which is why its last expression becomes the return value.

The semicolon mistake

Here is the most common function mistake in Rust, adding a semicolon to the last line:

src/main.rs
fn order_total(price: u32, quantity: u32) -> u32 {
price * quantity;
}

The compiler says:

Output
error[E0308]: mismatched types
--> src/main.rs:1:46
|
1 | fn order_total(price: u32, quantity: u32) -> u32 {
| ----------- ^^^ expected `u32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | price * quantity;
| - help: remove this semicolon to return this value
  1. mismatched types: you promised a u32 but returned something else.
  2. found (): () (an empty tuple, called the unit type) is Rust’s way of saying “nothing”. Because the last line ended in a semicolon, the function returns nothing.
  3. help: remove the semicolon. Exactly right!

Tip

If you see “expected u32, found ()” (or any type versus ()), check the last line of your function for an extra semicolon.

The return keyword

You can also return a value early with the return keyword. It’s handy when you know the answer before reaching the end:

src/main.rs
fn main() {
println!("{}", discounted_price(450, true));
println!("{}", discounted_price(450, false));
}
fn discounted_price(price: u32, has_loyalty_card: bool) -> u32 {
if !has_loyalty_card {
return price;
}
price - 50
}
Output
400
450
  1. ! means “not”. So !has_loyalty_card is true when the customer has no card.
  2. In that case, return price; leaves the function immediately with the full price.
  3. Otherwise we reach the last line, price - 50, which is returned with no semicolon and no return needed.

Don’t worry about if yet. It’s the star of the next lesson. Rust style is to use return only for early exits, and to let the last expression be the normal return value.

Note

Functions with no -> return (), the “nothing” value. That’s why print_welcome() doesn’t need a return type: it prints something, but doesn’t hand anything back.

Try it yourself

Write a function price_with_tax(cents: u32) -> u32 that adds 10% tax to a price in cents. Use integer maths: cents + cents / 10. Call it from main for a latte (450) and a croissant (325) and print both results.

Show solution
src/main.rs
fn main() {
let latte = price_with_tax(450);
let croissant = price_with_tax(325);
println!("Latte with tax: {latte} cents");
println!("Croissant with tax: {croissant} cents");
}
fn price_with_tax(cents: u32) -> u32 {
cents + cents / 10
}

Output:

Output
Latte with tax: 495 cents
Croissant with tax: 357 cents

325 / 10 is 32 in integer division (the .5 is dropped), so the croissant costs 357. Real tills have rules about rounding, but this is a good start. And notice: no semicolon on the last line of price_with_tax!

Recap

  • Define a function with fn name(params) -> ReturnType { body } and call it with name(arguments).
  • Every parameter needs a type, like price: u32.
  • An expression produces a value. A statement does something and produces no value.
  • The last expression in a function body (with no semicolon) is its return value. return exits early.
  • “expected u32, found ()” usually means an extra semicolon on the last line.

What’s next

Our functions can calculate, but they can’t really decide yet. In Control Flow you’ll learn if, loops and a first taste of match.

0 of 35 lessons complete

Search lessons

Type to search all lessons.