CodeToLive

Functions in Rust

Functions in Rust are reusable blocks of code that perform a specific task. They can take parameters and return values.

Defining a Function

Functions in Rust are defined using the fn keyword.


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

fn main() {
    greet("Alice");
}
      

Function Parameters

Functions can take parameters, which are variables passed to the function.


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

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

Returning Values

Functions can return values using the return keyword or implicitly.


fn multiply(a: i32, b: i32) -> i32 {
    a * b
}

fn main() {
    let result = multiply(5, 10);
    println!("Product: {}", result);
}
      

Returning Multiple Values

Functions can return multiple values using tuples.


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

fn main() {
    let (sum, product) = calculate(5, 10);
    println!("Sum: {}, Product: {}", sum, product);
}
      

Closures

Closures are anonymous functions that can capture variables from their environment.


fn main() {
    let add = |a: i32, b: i32| a + b;
    let result = add(5, 10);
    println!("Sum: {}", result);
}
      

Higher-Order Functions

Higher-order functions are functions that take other functions as parameters or return them.


fn apply_function(f: F, a: i32, b: i32) -> i32
where
    F: Fn(i32, i32) -> i32,
{
    f(a, b)
}

fn main() {
    let add = |a: i32, b: i32| a + b;
    let result = apply_function(add, 5, 10);
    println!("Result: {}", result);
}
      

Best Practices

Next: Ownership and Borrowing