Mastering Functions in Rust


Functions are the building blocks of any programming language, and Rust is no exception. You could write hugely complex programs without ever leaving the main function, but that would be utter maddness and you would be compelled to wear a straightjacket.

In this tutorial, we’re going to take a deep dive into functions in Rust, covering everything from defining functions to closures and everything in between.

Defining Functions

Defining functions in Rust is a piece of cake. You can define a function using the fn keyword followed by the function name, a list of parameters, and the return type. Here’s an example:

fn add(a: i32, b: i32) -> i32 {
    a + b
}

Let’s break this down a little and focus on the different parts of the function definition:

  1. fn: This is the keyword used to define a function in Rust.
  2. add: This is the name of the function.
  3. (a: i32, b: i32): These are the parameters that the function takes. In this case, the function add takes two parameters, a and b, both of type i32.
  4. -> i32: This is the return type of the function. In this case, the function add returns a value of type i32.

The body of the function is the expression a + b, which adds the two parameters together and returns the result.

Calling Functions

Once you’ve defined a function, you can call it from other parts of your code. Here’s an example of calling the add function we defined earlier:

fn main() {
    let result = add(5, 10);
    println!("The result is: {}", result);
}

In this example, we call the add function with the arguments 5 and 10, and store the result in a variable called result. We then use println! to print the result to the console.