9  Functions

Learn how to define and use your own functions in Rust.

We’ve already been modifying the main() function this whole time. We can create and use additional functions too.

In R, functions are yet another type of object that we create using <- function(). In Rust, they are declared using fn keyword. Just like everything else in Rust, arguments are typed. Arguments take the structure of arg: type.

Much like R, the last object in a function body is return automatically. You do not need to use the return keyword unless you are performing an early return.

fn name_of_function(arg1: ArgType) -> ReturnType {
    // function body
    my_return_object
}

Example

Identifying if a number is odd or even isn’t always so easy!

is-odd npm

First define a function called is_even() that takes an i32 (integer) and returns a bool.

It may not be entirely obvious, but functions can be declared outside of the main() function.

fn is_even(x: i32) -> bool {
    x % 2 == 0
}

We can use our already defined function inside of another:

fn is_odd(x: i32) -> bool {
    !is_even(x)
}

Exercise

Create a function called mean() that calculates the mean of a Vec<f64>.

  • In main(), create a vector x with 5 or more f64 values.
  • Call mean(x) and print the result.

Use x.len() to get the length and as f64 to convert it to a float.

Solution

View solution
fn mean(x: Vec<f64>) -> f64 {
    let mut total = 0.0;
    let n = x.len();
    for xi in x {
        total += xi;
    }
    total / n as f64
}

fn main() {
    let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    let result = mean(x);
    println!("Mean is: {}", result);
}