Functions and closures

Define functions with fn, typed parameters and return values, tuples, and closures.

Runs in Zerethon IDE · Rust 1.87 Official Rust documentation ↗
main.rs
fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

fn stats(numbers: &[i32]) -> (i32, i32, f64) {
    let low = *numbers.iter().min().unwrap();
    let high = *numbers.iter().max().unwrap();
    let sum: i32 = numbers.iter().sum();
    (low, high, sum as f64 / numbers.len() as f64)
}

fn main() {
    println!("{}", greet("Ada"));
    let (low, high, mean) = stats(&[4, 8, 6]);
    println!("{low} {high} {mean}");

    let offset = 10;
    let add = |x: i32| x + offset;
    let square = |x: i32| x * x;
    println!("{} {}", add(5), square(9));
}

Output

Hello, Ada!
4 8 6
15 81
  • Parameter types are required; the return type follows ->.
  • The last expression without ; is returned. Adding ; to it turns it into a statement and the function returns () instead — a common mismatched types error.
  • A tuple returns several values at once; let (a, b, c) = ... unpacks it.
  • A closure |x| x + offset can use variables from the place where it is written.