Functions in Rust

A function is named code that takes values (parameters) and hands over a result. It is written fn name(param: Type, ...) -> ResultType { ... }. Every…

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

Expressions and statements

Rust tells two kinds of line apart:

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

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

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

⚠️ The errors you will see most while writing functions

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.

What you will learn