Lesson 05

Functions and Modules

Organize code into reusable functions and simple modules.

Learning objectives

Functions

Functions help you break a program into smaller parts. In Rust, function parameters must include type annotations.

Returning Values

Rust can return the final expression in a function without using the return keyword. This style is common in Rust code.

Modules

Modules help group related code. As your programs grow, modules make the project easier to understand and maintain.

Example code

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

fn print_result(value: i32) {
    println!("Result: {}", value);
}

fn main() {
    let answer = add(12, 8);
    print_result(answer);
}
Practice task: Create a function named multiply that accepts two integers and returns their product.