Functions in Rust

Functions are the building blocks of readable, maintainable code. In Rust, functions are declared using the fn keyword and follow a clear, consistent syntax.

Basic Function Syntax

Here's how you define a simple function in Rust:

fn greet() {
    println!("Hello, world!");
}

To call this function, you simply write greet();

Functions with Parameters

Functions can take parameters, which must have type annotations:

fn greet_person(name: &str) {
    println!("Hello, {}!", name);
}

Return Values

Functions can return values. The return type is declared after an arrow ->:

fn add(x: i32, y: i32) -> i32 {
    x + y  // Note: no semicolon here!
}

Multiple Parameters

You can have multiple parameters with different types:

fn calculate_rectangle_area(width: f64, height: f64) -> f64 {
    width * height
}

Practice Time!

Try writing a function that:

  1. Takes two numbers as parameters
  2. Returns their sum
  3. Prints the result
fn main() {
    let result = add_numbers(5, 3);
    println!("The sum is: {}", result);
}

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

Key Points to Remember

  • Functions start with fn
  • Parameter types must be declared
  • Return types are declared with ->
  • The last expression in a function is implicitly returned
  • Early returns use the return keyword
  • Function names use snake_case by convention

Now it's your turn to experiment with functions in the playground below!