Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Functions

A function is a named recipe. You write the steps once, give them a name, and then use the name whenever you need those steps, as many times as you like. You already know one function, main. Now let us write our own.

fn greet() {
    println!("Hello there!");
    println!("Welcome to Rust.");
}

fn main() {
    greet();
    greet();
}
Output
Hello there!
Welcome to Rust.
Hello there!
Welcome to Rust.

The function is defined with fn, a name, round brackets and a body in curly brackets. Writing greet(); calls the function: Rust jumps into it, runs its steps, and comes back. It does not matter whether a function is written above or below main.

Parameters: giving a function inputs

A function becomes much more useful when it can work on different values each time. The values it receives are called parameters, listed in the round brackets. In Rust you must always write each parameter's type:

fn greet(name: &str, times: u32) {
    for _ in 0..times {
        println!("Hi, {}!", name);
    }
}

fn main() {
    greet("Kabir", 2);
    greet("Zoya", 1);
}
Output
Hi, Kabir!
Hi, Kabir!
Hi, Zoya!

The underscore in for _ in means we do not need the counter's value; we only want to repeat.

Return values: getting an answer back

A function can also give a value back to whoever called it. The type of that value comes after an arrow ->. The last expression in the body, written without a semicolon, is the value returned:

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

fn is_adult(age: u32) -> bool {
    age >= 18
}

fn main() {
    let room = area(4.0, 3.5);
    println!("The room is {} square metres", room);
    println!("Is 20 an adult? {}", is_adult(20));
}
Output
The room is 14 square metres
Is 20 an adult? true

The semicolon matters

This is the one detail that trips everybody up at first. width * height without a semicolon is an expression: it produces a value, which becomes the function's answer. Add a semicolon and it becomes a statement, which produces nothing, and the compiler will complain that the function promised an f64 but gave back nothing. If you ever see the error "mismatched types" pointing at the end of a function, look for a stray semicolon.

You can also leave a function early with return value;. That is handy inside an if, for example to stop as soon as the answer is known.

Practice exercises

  1. Write a function square(n: i32) -> i32 and use it to print the squares of 1 to 5.
  2. Write celsius_to_fahrenheit(c: f64) -> f64 and convert 0, 37 and 100 degrees.
  3. Add a semicolon after the last line of area and read the error and the hint.