Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 1 · Fundamentals

    1.3Functions, expressions & statements

    How to declare Rust functions, why the last expression is the return value, and how if and blocks produce values where you'd otherwise reach for a ternary.

    About 20 minutesBeginner

    On this page
    1. Concept map
    2. Declaring a function
    3. The last expression is the return value
    4. Unit and never: () and !
    5. Which one should I use?
    6. Under the hood
    7. Common pitfalls
    8. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Declaring a functionfunction add(a: number, b: number): numberstatic int Add(int a, int b)fn add(a: i32, b: i32) -> i32
    Parameter and return typesParameter types required, return type can be inferredAlways writtenAlways written on fn; only local variables and closures are inferred
    Returning a valuereturn x;, or an arrow function's expression bodyreturn x;, or an expression-bodied member => xThe last expression, with no semicolon; return for early exits
    Returning nothingvoidvoid() (unit): leave out ->
    A function that never returnsneverNo type; [DoesNotReturn] or a throw expression! (never)
    Choosing between two valuescond ? a : bcond ? a : b, or a switch expressionif cond { a } else { b }

    Rust functions look familiar: a name, typed parameters, a return type and a body. The difference is in the body. Almost everything in Rust is an expression that produces a value, including if and { } blocks, and a function returns the value of its last expression. Once that clicks, you’ll stop missing the ternary operator.

    Declaring a function

    fn declares a function. Parameter types and the return type, after ->, are always written: Rust never infers a function’s signature, even when it could. The signature is the contract, so a mistake inside the body can’t silently change what callers see.

    TypeScript
    math.ts
    function add(a: number, b: number): number {
      return a + b;
    }
    
    const twice = (n: number): number => n * 2;
    
    console.log(add(2, 3), twice(4));
    C#
    Math.cs
    Console.WriteLine($"{Add(2, 3)} {Twice(4)}");
    
    static int Add(int a, int b)
    {
        return a + b;
    }
    
    static int Twice(int n) => n * 2;
    Rust
    fn add(a: i32, b: i32) -> i32 {
        a + b // no `return`, no semicolon: this is the return value
    }
    
    fn twice(n: i32) -> i32 {
        n * 2
    }
    
    fn main() {
        println!("{} {}", add(2, 3), twice(4));
    }

    Output

    5 8

    A few things carry over directly: functions can be declared in any order, as with TypeScript function declarations, as in C#, and names use snake_case. Rust has no arrow syntax for named functions, so twice is a normal fn with a one-line body. Anonymous functions do exist, written |n| n * 2; Reading Rust’s symbols introduces them.

    The last expression is the return value

    A statement does something and produces no value: let x = 5; is one. An expression produces a value: a + b, twice(4), and in Rust also if and { } blocks. A block’s value is its last expression, if that expression has no semicolon after it. A function body is a block, so its last expression is what the function returns. This is called the tail expression.

    return still exists. Use it to leave early, typically after checking for bad input:

    TypeScript
    label.ts
    function label(score: number): string {
      if (score < 0) {
        return "invalid";
      }
      return score >= 50 ? "pass" : "fail";
    }
    
    console.log(label(72), label(30), label(-1));
    C#
    Label.cs
    Console.WriteLine($"{Label(72)} {Label(30)} {Label(-1)}");
    
    static string Label(int score)
    {
        if (score < 0)
        {
            return "invalid";
        }
        return score >= 50 ? "pass" : "fail";
    }
    Rust
    fn label(score: i32) -> &'static str {
        if score < 0 {
            return "invalid"; // early exit
        }
        if score >= 50 { "pass" } else { "fail" } // tail expression
    }
    
    fn main() {
        println!("{} {} {}", label(72), label(30), label(-1));
    }

    Output

    pass fail invalid

    &'static str is the type of a string literal: text that’s built into the program and is valid for as long as it runs. Reading Rust’s symbols explains the & and the 'static.

    The ternary cond ? a : b doesn’t exist in Rust, because if already produces a value. Both branches must have the same type, and the else is required whenever the value is used: otherwise there’d be no value when the condition is false.

    Any block can produce a value, which keeps temporary variables out of the surrounding scope:

    TypeScript
    total.ts
    const price = 20;
    const shipping = price >= 50 ? 0 : 5;
    const total = price + shipping;
    console.log(total);
    C#
    Total.cs
    var price = 20;
    var shipping = price >= 50 ? 0 : 5;
    var total = price + shipping;
    Console.WriteLine(total);
    Rust
    let total = {
        let price = 20;
        let shipping = if price >= 50 { 0 } else { 5 };
        price + shipping // the block's value
    };
    println!("{total}");

    Output

    25

    Mental model shiftExpressions, not statements

    In TypeScriptC#, if is a statement, so choosing a value needs a different tool: the ternary, or a switch expression. In Rust, if, match, blocks and loops are all expressions. You use the same if to run code and to pick a value.

    Unit and never: () and !

    A function with no -> returns (), the empty tuple, called unit. It plays the role of void, but it’s a real type with exactly one value, also written (). That matters later: generic code can return () like any other type, much as TypeScript lets you write Promise<void>, where C# needs both Action and Func<T>.

    A function that never returns, because it always panics, exits the process or loops forever, has return type !, the never type. It’s TypeScript’s never.C# has no such type: a helper that always throws still has to declare a return type, so here it’s made generic to fit in the ternary.

    TypeScript
    divide.ts
    function fail(message: string): never {
      throw new Error(message);
    }
    
    function divide(a: number, b: number): number {
      return b !== 0 ? Math.trunc(a / b) : fail("division by zero");
    }
    
    console.log(divide(10, 2));
    C#
    Divide.cs
    Console.WriteLine(Divide(10, 2));
    
    static T Fail<T>(string message) => throw new InvalidOperationException(message);
    
    static int Divide(int a, int b) => b != 0 ? a / b : Fail<int>("division by zero");
    Rust
    fn fail(message: &str) -> ! {
        panic!("{message}");
    }
    
    fn divide(a: i32, b: i32) -> i32 {
        if b != 0 {
            a / b
        } else {
            fail("division by zero") // type `!`: fits where an i32 is expected
        }
    }
    
    fn main() {
        println!("{}", divide(10, 2));
    }

    Output

    5

    Because a ! expression never produces a value, it fits wherever any type is expected: the else branch above has type !, and the if as a whole is still an i32. return, break, continue, panic!(...) and std::process::exit(1) all have type !, which is why let n = if ok { 5 } else { return }; compiles.

    Which one should I use?

    WhatWhenWhyHow
    Tail expressionReturning the function’s result at the end, which is most of the time.It’s the idiom; clippy flags a return x; on the last line as needless.Write the value last with no semicolon: a + b
    return x;Leaving early: bad input, a value found, nothing left to do.Saves nesting the rest of the function in an else.if score < 0 { return "invalid"; }
    if as an expressionChoosing between two values.Replaces the ternary, with full blocks in each branch.let fee = if total >= 50 { 0 } else { 5 }; Both branches must have the same type.
    Block { ... } as an expressionA value that takes a few steps to compute.Temporary variables stay inside the block.let total = { let tax = 3; price + tax };
    No -> (returns ())Functions that only do something: print, write, change a &mut argument.Same as void.fn log(message: &str) { println!("{message}"); }
    -> !Functions that always panic, exit or loop forever.Callers can use them where any type is expected.fn fail(message: &str) -> ! { panic!("{message}") }

    The confusing part is the semicolon. A semicolon turns an expression into a statement and throws its value away. So a + b at the end of a function returns the sum, and a + b; returns (). If the signature says -> i32, the second one doesn’t compile. The rest of the time, a missing or extra semicolon is a syntax error you’ll fix in seconds.

    Rule of thumb: end every function that returns a value with its result as a bare expression, use return only to leave early, and use if ... else wherever you’d write a ternary. When the compiler says “expected i32, found ()”, look for a semicolon after the last line.

    Under the hood

    Here’s that classic mistake. The body ends with a statement, so the block’s value is ():

    fn add(a: i32, b: i32) -> i32 {
        a + b;
    }
    
    fn main() {
        println!("{}", add(2, 3));
    }

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> add.rs:1:27
      |
    1 | fn add(a: i32, b: i32) -> i32 {
      |    ---                    ^^^ expected `i32`, found `()`
      |    |
      |    implicitly returns `()` as its body has no tail or `return` expression
    2 |     a + b;
      |          - help: remove this semicolon to return this value

    The compiler checks the type of the function’s last expression against the declared return type. It even suggests the fix: remove the semicolon.

    The same rules explain why chained assignment doesn’t work. In TypeScriptC#, a = b = 5 works because an assignment is an expression whose value is the assigned value. In Rust, an assignment like b = 5 is an expression whose value is (), so a = b = 5 tries to store () in a, and fails with the same E0308. And let is a statement, so it has no value at all.

    At runtime none of this costs anything. if as an expression compiles to the same branch, or a branch-free conditional move, that a ternary would in C#. A function returning () returns nothing at all: () takes zero bytes.

    Common pitfalls

    Common pitfallForgetting the return type

    In TypeScript, leaving out the return type lets the compiler infer it.In C#, a method without a return type doesn’t compile: you write void when there’s nothing to return. In Rust, leaving out -> means the function returns (), so returning a number is an error:

    fn add(a: i32, b: i32) {
        a + b
    }
    
    fn main() {
        add(2, 3);
    }

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> main.rs:2:5
      |
    1 | fn add(a: i32, b: i32) {
      |                       - help: try adding a return type: `-> i32`
    2 |     a + b
      |     ^^^^^ expected `()`, found `i32`

    Write the return type on every function that produces a value: fn add(a: i32, b: i32) -> i32.

    Common pitfallAn if used as a value needs an else

    let fee = if total >= 50 { 0 }; doesn’t compile: when the condition is false, there’s no value to store. Add the else branch. Both branches must also have the same type: if ok { 1 } else { "one" } is an error, where TypeScript would infer a union type.

    let total = 40;
    let fee = if total >= 50 {
        0
    };
    println!("{fee}");

    Rust doesn't compile this: error E0317

    error[E0317]: `if` may be missing an `else` clause
     --> main.rs:2:11
      |
    2 |   let fee = if total >= 50 {
      |  _______________^
    3 | |         0
      | |         - found here
    4 | |     };
      | |_____^ expected integer, found `()`
      |
      = note: `if` expressions without `else` evaluate to `()`
      = help: consider adding an `else` block that evaluates to the expected type

    Common pitfallNo overloads, default or optional parameters

    TypeScript has optional parameters (name?: string), defaults (name = "world") and overload signatures.C# has optional parameters with defaults, and overloads. Rust has none of them: each function has one fixed list of parameters. Give variants different names, as the standard library does with String::new() and String::with_capacity(10), or take an Option (Module 6).

    Try it yourself

    Exercise: port this to Rust

    Port this function to Rust without using return.

    Starting code in TypeScript
    fizzbuzz.ts
    function fizzBuzz(n: number): string {
      if (n % 15 === 0) {
        return "FizzBuzz";
      } else if (n % 3 === 0) {
        return "Fizz";
      } else if (n % 5 === 0) {
        return "Buzz";
      }
      return String(n);
    }
    
    console.log(fizzBuzz(3), fizzBuzz(5), fizzBuzz(15), fizzBuzz(7));
    Starting code in C#
    FizzBuzz.cs
    Console.WriteLine($"{FizzBuzz(3)} {FizzBuzz(5)} {FizzBuzz(15)} {FizzBuzz(7)}");
    
    static string FizzBuzz(int n)
    {
        if (n % 15 == 0)
        {
            return "FizzBuzz";
        }
        else if (n % 3 == 0)
        {
            return "Fizz";
        }
        else if (n % 5 == 0)
        {
            return "Buzz";
        }
        return n.ToString();
    }

    Expected output

    Fizz Buzz FizzBuzz 7
    Show a hint

    Write one if / else if / else chain as the tail expression of fizz_buzz. Each branch is a value with no semicolon and no return, and every branch must be a String: use String::from for the words and n.to_string() for the number.

    Show a solution
    fn fizz_buzz(n: i32) -> String {
        if n % 15 == 0 {
            String::from("FizzBuzz")
        } else if n % 3 == 0 {
            String::from("Fizz")
        } else if n % 5 == 0 {
            String::from("Buzz")
        } else {
            n.to_string()
        }
    }
    
    fn main() {
        println!(
            "{} {} {} {}",
            fizz_buzz(3),
            fizz_buzz(5),
            fizz_buzz(15),
            fizz_buzz(7)
        );
    }

    The whole if / else if / else chain is one expression, and it's the last thing in the function, so its value is the return value. Each branch produces a String, so the chain does too. No return keyword is needed anywhere.