Intro

Rust is a functional language, it may or may not be shocking to discover that functions are a big part of the language.

A function is defined with the fn keyword. fn is pronounced: fun 🥳

rust
// Function with no parameters or return value
fn stuff() {
    println!("stuff"); // => stuff
}

// Function with parameters that returns an i32
fn add(i: i32, j: i32) -> i32 {
    // return i + j; // supported, but not preferred.
    i + j // bare tail expression is perferred.
}

// The `main` function is the programs entry point.
fn main() {
    stuff(); // call a function.
    println!("{}", add(1, 2)); // => 3
}

Considerations

  • Functions are defined in snake_case by convention.
  • Type annotations are required for any parameters.
  • If the function returns something, the return type must be specified.
  • A functions name, its parameters and return type make up a functions signature .
  • The main function is the entrypoint to the program.
  • The last statement in a function is automatically returned, this is known as a tail expression .
  • The return keyword is not required unless exiting before the tail expression .
  • The bare tail expression format is the preferred Rust convention.
  • The terminating semicolon ; is not required for a returned value.
  • Functions do not support default parameter assignment.
  • Functions do not support named parameters, all parameters are positional.
  • Functions must be called with all the parameters in the correct order.
# rust