Skip to content
Theory · Functions · lesson 1 of 4

Functions and parameters

What you'll learn

What you'll learn:

  • declare functions with fn and call them with arguments;
  • write the type of every parameter and the return type after ->;
  • tell an expression from a statement and get the value of a block;
  • explain why an extra ; at the end of a function breaks the build.
A multicooker area takes bars of three and four squares, and a three-by-four tile comes out of its spout labelled -> i32

Picture a kitchen appliance, say a multicooker. You put the ingredients in, press a button and get a finished dish. You don't need to know how the appliance works inside: it is enough to know what to put in and what comes out.

A function in a program works the same way. It is a named piece of code: it receives values, does something with them and hands back a result. You write the function's code once and call it by name as many times as you like. If the formula changes, you fix it in one place, not in every line that needs it.

You already know one function, main. Now let's write our own: it computes the area of a room from its width and length.

Rust
fn area(width: i32, length: i32) -> i32 {
    width * length
}

fn main() {
    let kitchen = area(3, 4);
    let hall = area(5, 2);
    println!("{kitchen} {hall}"); // 12 10
}

Let's go through the program line by line:

  1. fn area(width: i32, length: i32) -> i32 { declares the function area. It takes two whole numbers and returns a whole number.
  2. width * length is the function's body: it multiplies the sides, and the product becomes the result.
  3. area(3, 4) in main calls the function: 3 goes into width, and 4 into length.
  4. The function hands back 12, and let kitchen = puts that number into kitchen.
  5. The second call, area(5, 2), works with other numbers and hands back 10.
  6. println! prints 12 10.

Declaring a function

A function declaration has five parts:

  • fn, the keyword that starts the declaration;
  • area, the function's name;
  • (width: i32, length: i32), the parameters in parentheses: what goes into the appliance;
  • -> i32, the return type after the arrow: what the appliance hands back;
  • the body in curly braces: what the appliance does with the ingredients.

The first line of the declaration, from fn to {, is called the signature. It is the label on the appliance: it alone tells you what the function takes and what it returns. The function's result is the last expression of its body, written without a semicolon: here it is width * length.

A function name is written in lowercase letters, with underscores between the words: area, print_total. The compiler accepts the name printArea, but it gives a warning: warning: function `printArea` should have a snake case name.

Calling a function

To call a function, you write its name and the arguments in parentheses: area(3, 4). While the function runs, main waits. When the function finishes, the call is replaced by its result. That is why a call can go anywhere a number fits: in a let, in a println! or inside another expression, such as area(3, 4) * 2.

You can declare functions in any order. In the example area stands above main, but it could stand below it: the compiler reads the whole file before it checks the calls. Execution still starts in main, and other functions run only when they are called.

Parameters and arguments

Values are named differently in the declaration and in the call:

  • a parameter is a name in the function's declaration: width in fn area(width: i32, length: i32);
  • an argument is the value passed at the call: 3 in area(3, 4).

Arguments take the places of the parameters in order: the first argument goes into the first parameter, the second into the second. The number of arguments must match the number of parameters. The call area(3) does not compile: error[E0061]: this function takes 2 arguments but 1 argument was supplied.

A type for every parameter

Every parameter has its type after a colon: width: i32. In the line let apples = 3; you can leave the type out, because the compiler infers it from the value. A signature has no type inference: even if the function is only ever called with whole numbers, the compiler does not take the parameter's type from the call.

Interviewers like to ask this: why does Rust require parameter types when it infers types inside a function by itself? The answer has two parts:

  • the signature is a contract with the calling code, and its one line shows what the function takes and what it returns;
  • type inference works inside one function, so editing the body never quietly changes what the function accepts.

A parameter gets a copy

A number passed as an argument is copied into the parameter, and the function works with its own copy. The function can change the copy if the parameter is declared with mut: that is a box with an open lid. Let's see:

Rust
fn countdown(mut n: i32) {
    while n > 0 {
        println!("{n}");
        n -= 1;
    }
}

fn main() {
    let start = 3;
    countdown(start);
    println!("start = {start}"); // start = 3
}

Step by step:

  1. countdown(start) copies 3 from start into the parameter n.
  2. The loop prints n and lowers it by one: n -= 1 is the same as n = n - 1. This way it prints 3, 2 and 1, each number on its own line.
  3. After the call the variable start still equals 3: the function changed only its own copy.

countdown has no ->: it returns nothing and only prints. The calling code needs no mut, and start is declared without it.

Here the appliance picture falls short. A multicooker uses up the ingredients, but a function gets a copy of the number, and the calling code keeps its own.

Common mistake

The type was written once for two parameters, as if it applied to both:

Rust
fn area(width, length: i32) -> i32 { // ✗
    width * length
}

fn main() {
    println!("{}", area(3, 4));
}
TEXT
error: expected one of `:`, `@`, or `|`, found `,`

The program does not compile. After the name width the compiler expects a colon and a type, but finds a comma. Rust has no shared type notation for several parameters, and the help: hint in the full message suggests giving the parameter a type. The fixed signature is fn area(width: i32, length: i32) -> i32.

Key points

  • A function is declared with fn: a name in lowercase letters with underscores, parameters in parentheses, the return type after ->, the body in curly braces.
  • A parameter is a name in the declaration, an argument is a value in the call; arguments take the places of the parameters in order.
  • Every parameter has its type written out: the compiler does not infer types in a signature.
  • A number passed as an argument is copied into the parameter, and the function changes only its own copy.