Functions

They allow us to group and reuse statements, with the possibility to return values

Functions can be defined before and after the main function (no function prototypes, unlike C)
functions

Note: Rust uses snake case names (like a_b, my_function...);

cargo clippy will get angry if you don't do the same

functions

Here is the definition and usage of a function that prints "Hello World!":


                fn main() {
                    hello_world();
                }

                fn hello_world() {
                    println!("Hello World!"):
                }
        
functions

Parameters

functions

Example:


            fn main() {
                let a = 6;
                let b = 8;

                pythagoras(a, b); // Prints "a^2 + b^2 = 100"
            }

            fn pythagoras(a: i32, b: i32) {
                println!("a^2 + b^2 = {}", a*a + b*b);
            }
        
functions

Returning values

We often need a function to return a value after its execution. To do so:

functions

Let's change the previous example:


            fn main() {
                let a = 6;
                let b = 8;

                let res = pythagoras(a, b);

                println!("a^2 + b^2 = {res}");
            }

            fn pythagoras(a: i32, b: i32) -> i32 {
                a*a + b*b
            }
        
functions

As in other programming languages, we can use recursion to perform tasks:


            fn main(){
                let n = 4;

                let res = fibonacci(n);

                println!("{res}"); // Prints "5"
            }

            //Function that calculates the nth Fibonacci number
            fn fibonacci(n: u64) -> u64 {
                if n <= 1 {
                    return 1;
                }

                fibonacci(n - 1) + fibonacci(n - 2)
            }
        
Note the missing colon at the bottom of the function