TExcelTAD
Home › Rust › Rust Functions

Rust Functions

A function is a named block of code that performs one job. Functions let you write logic once and reuse it, give a meaningful name to a piece of work, and break a big program into small, understandable parts.

You have already been writing one function in every program: main. Now it's time to write your own.

Defining and calling a function

Functions are declared with the fn keyword, followed by a name, parentheses and a body in curly braces. Rust uses snake_case for function names: lowercase words separated by underscores.

rust · try it yourself
fn print_banner() {
    println!("=====================");
    println!("  Welcome to ExcelTAD");
    println!("=====================");
}

fn main() {
    print_banner();
    println!("Let's learn about functions.");
    print_banner();
}
=====================
  Welcome to ExcelTAD
=====================
Let's learn about functions.
=====================
  Welcome to ExcelTAD
=====================

It does not matter whether print_banner is defined above or below main — Rust finds functions anywhere in the file.

Parameters

Parameters let you pass values into a function. Each parameter needs a name and a type; Rust never guesses parameter types.

rust · try it yourself
fn greet(name: &str, times: u32) {
    for _ in 0..times {
        println!("Hello, {}!", name);
    }
}

fn main() {
    greet("Ana", 2);
    greet("Ben", 1);
}
Hello, Ana!
Hello, Ana!
Hello, Ben!

&str is a borrowed piece of text (a string slice) and u32 is an unsigned 32-bit integer. The _ in the for loop means "I don't need the loop counter".

Return values

To send a value back, declare the return type after an arrow ->. The last expression in the body — written without a semicolon — is the value the function returns.

rust · try it yourself
fn square(x: i32) -> i32 {
    x * x
}

fn area_of_rectangle(width: f64, height: f64) -> f64 {
    width * height
}

fn main() {
    let s = square(7);
    println!("7 squared is {}", s);
    println!("Area: {}", area_of_rectangle(2.5, 4.0));
}
7 squared is 49
Area: 10

Note: If you add a semicolon — x * x; — the line becomes a statement that produces nothing, and the compiler reports "mismatched types: expected i32, found ()". This is one of the most common beginner mistakes, and the compiler even suggests removing the semicolon.

Statements vs expressions

This distinction matters a lot in Rust:

Produces a value? Example
Expression yes 5, a + b, square(3), if x > 0 { 1 } else { -1 }
Statement no let y = 6;, println!("hi");

Because a block { ... } is also an expression, you can compute a value in several steps and use the last line as the result.

Returning early with return

You can leave a function before the end with the return keyword. This is useful for handling special cases first.

rust · try it yourself
fn describe_age(age: u32) -> &'static str {
    if age < 13 {
        return "child";
    }
    if age < 20 {
        return "teenager";
    }
    "adult"
}

fn main() {
    for age in [8, 15, 42] {
        println!("{} -> {}", age, describe_age(age));
    }
}
8 -> child
15 -> teenager
42 -> adult

The return type &'static str means "a string slice that lives for the whole program" — string literals like "child" are exactly that. You'll learn about the 'static part in the Lifetimes chapter.

Returning more than one value

A function returns a single value, but that value can be a tuple holding several pieces:

rust · try it yourself
fn min_max(numbers: &[i32]) -> (i32, i32) {
    let mut min = numbers[0];
    let mut max = numbers[0];
    for &n in numbers {
        if n < min {
            min = n;
        }
        if n > max {
            max = n;
        }
    }
    (min, max)
}

fn main() {
    let data = [4, -2, 17, 9, 0];
    let (low, high) = min_max(&data);
    println!("Lowest: {}, highest: {}", low, high);
}
Lowest: -2, highest: 17

&[i32] is a slice — a borrowed view of a list of i32 values. It accepts arrays and vectors of any length.

Summary

  • Declare functions with fn name(param: Type) -> ReturnType { ... }.
  • Every parameter needs a type annotation.
  • The final expression (no semicolon) is the return value; return leaves early.
  • Functions with no -> return the unit type ().

Test yourself

What does this function return? fn f() -> i32 { 10 }

  1. Nothing
  2. 10
  3. ()
  4. It does not compile

Why does fn double(x: i32) -> i32 { x * 2; } fail to compile?

  1. x must be mutable
  2. The semicolon turns the last line into a statement, so the function returns ()
  3. Functions cannot multiply
  4. Parameters can't be named x

Which is a correct function signature that takes two f64 values and returns an f64?

  1. fn avg(a, b) -> f64
  2. fn avg(a: f64, b: f64): f64
  3. fn avg(a: f64, b: f64) -> f64
  4. func avg(f64 a, f64 b) f64