We define a function in Rust by entering fn followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends.

Rust doesn’t care where you define your functions, only that they’re defined somewhere in a scope that can be seen by the caller. (like hoisting in js)

In function signatures, you must declare the type of each parameter.

fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {x}");
}

we must declare return type after an arrow (->).

You can return early from a function by using the return keyword and specifying a value, but most functions return the last expression implicitly (more details in statements & expressions). Here’s an example of a function that returns a value:


fn five() -> i32 {
    5
}

fn main() {
    let x = five();

    println!("The value of x is: {x}");
}

if we return nothing from a function we get (), the unit type.