Labs ICT
โญ Pro Login

Functions

Writing functions with parameters and return values.

Functions

Functions in Rust are declared using the fn keyword. Every function parameter in Rust must have a type annotation. This makes the code more explicit and helps the compiler understand what's happening.

When it comes to return values, Rust has an interesting approach. The last expression in a function body is automatically the return value. You don't need the return keyword for this. However, if you do use return, you need a semicolon after it. This is why semicolons matter in Rust.

Functions in Rust can return multiple values using tuples. This is really useful when you need to return more than one piece of data from a function. Functions are also first-class values in Rust, meaning you can pass them as arguments to other functions and store them in variables.

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

// Function with return value
fn add(a: i32, b: i32) -> i32 {
    a + b // No semicolon = return value
}

// Function returning multiple values
fn get_values() -> (i32, f64, &str) {
    (42, 3.14, "hello")
}

fn main() {
    greet("Rust developer");
    
    let sum = add(5, 3);
    println!("5 + 3 = {}", sum);
    
    let (num, pi, text) = get_values();
    println!("Values: {}, {}, {}", num, pi, text);
}
Try it Yourself ->

๐Ÿงช Quick Quiz

How do functions return values in Rust?