Skip to content
Theory · Functions · lesson 3 of 4

Expressions and return values

In the previous lesson the function area handed back the product width * length, and there was no semicolon after it. Let's see why the result is written this way and what a single semicolon changes.

Recall the kitchen appliance: ingredients in, a dish out. The appliance hands out the finished dish at the last step.

Now imagine that at the last step the appliance seals the dish in a box nobody will open. The dish is cooked, but you get an empty box. A semicolon after the last line of a function does exactly that.

To see how this works, you need to tell apart two kinds of code: expressions and statements.

Expressions and statements

As you already know, an expression is code that evaluates to a value. A statement works differently.

Expression

Rust has many kinds of expressions:

  • a number 5 or a variable name width;
  • arithmetic, such as width * length;
  • a function call area(3, 4): its value is what the function returned;
  • if with an else branch and loop with break.

Statement

A statement performs an action but gives no value. Statements look like this:

  • let x = 5; creates a variable;
  • fn declares a function;
  • an expression with a semicolon at the end, such as println!("hi"); or n -= 1;.

Since let has no value, it cannot go where a value is expected. The line let x = (let y = 6); does not compile: error: expected expression, found `let` statement.

A semicolon throws the value away

If you put ; after an expression, it becomes a statement: the value is computed and thrown away right away. This is how you write code that you need for its action, not for its value: printing with println! or changing a variable with +=. This is the box nobody will open.

The value of a block

Curly braces inside a function form a block, and a block is an expression too. Its value is the last expression inside, if there is no ; after it:

Rust
fn main() {
    let width = 3;
    let area = {
        let length = width * 2;
        width * length
    };
    println!("{area}"); // 18
}

Let's see where the value comes from:

  1. let area = { opens a block: the value of area will be the value of the block.
  2. let length = width * 2; is a statement: it creates the variable length with the value 6, but gives no value itself.
  3. width * length comes last and has no ;, so 18 becomes the value of the block.
  4. } closes the block, and the ; after it ends the let area statement.
  5. println! prints 18.

The variable length lives only inside the block. Here the block is like a small appliance right in the code: inside it prepares intermediate values, and it hands out one.

If the last line of a block ends with ;, there is nothing to hand out, and the value of the block is the empty tuple (). It is a tuple without a single element: this is how Rust shows that there is no value.

Rust
let report = {
    let total = 3 * 4;
    println!("total = {total}"); // total = 12
};
println!("{report:?}"); // ()

Here println! with a semicolon is a statement. The block printed a line but handed out no value, and report holds ().

A function body is a block too

A function body is the same kind of block in curly braces, and the same rule applies to it. The function's value is the body's last expression without ;, and -> i32 in the signature says what type that value has. Once the last expression is evaluated, the function ends, and its call is replaced by that value.

Any expression can come last, even an if with else: then the function's value is the value of the chosen branch. Press "Next step" and watch the frames: every call has its own frame, and when it closes, the value of the last expression reaches main.

LiveThe value of a functionstep 1 of 13 · frames: 1

main calls square(4) and waits for its value.

Watch which value reaches main when a call's frame closes

An early exit with return

Sometimes the result is known before the function ends. Then you hand it back with the keyword return: it leaves the function at once, and the lines below it do not run.

Rust
fn ticket_price(age: i32) -> i32 {
    if age < 7 {
        return 0;
    }
    300
}

fn main() {
    println!("{}", ticket_price(5)); // 0
    println!("{}", ticket_price(30)); // 300
}

Let's go through both calls:

  1. ticket_price(5): the condition age < 7 is true, and return 0; leaves the function at once with the value 0. The line 300 is never reached.
  2. ticket_price(30): the condition is false, the block with return is skipped, and the last expression 300 becomes the function's value.

After return 0 the semicolon does no harm: return leaves the function before the value could be thrown away. You may also write return 300; on the last line, but that is not the custom. Interviewers ask when return is needed. The answer: for an early exit from the middle of a function, while at the end an expression without ; is enough.

A function without ->

A function without -> has a result too: the empty tuple (). The notation fn main() means exactly fn main() -> (). Many languages have the word void for this, and in Rust () plays its role. If the body of such a function ends with ;, all is well: it promises () anyway.

Common mistake

A semicolon was put after the last expression of a function that promises an i32:

Rust
fn square(x: i32) -> i32 {
    x * x; // ✗
}

fn main() {
    println!("{}", square(4));
}
TEXT
error[E0308]: mismatched types

The program does not compile, and it never gets to run. x * x; is a statement: the product is computed and thrown away, and the body has no last expression left. Such a body gives (), while the signature promises an i32.

Here the appliance picture falls short. An appliance would silently hand over the empty box, but Rust checks the body against the signature: it adds no default value such as 0 and stops the build.

In the full message the compiler explains that the body implicitly returns (), and it hints: remove this semicolon to return this value. Remove the semicolon, and the function returns 16. This is a classic interview question: an extra ; turns the function's result into (), and the build fails with error E0308.

Key points

  • An expression gives a value, a statement does not; let is a statement, and ; turns an expression into a statement.
  • The value of a block and of a function body is the last expression without ;; if the last line ends with ;, the value is ().
  • return is for an early exit, while at the end of a function an expression without ; is enough.
  • An extra ; after the last expression of a function with -> i32 is error E0308: the body gives () instead of i32.