RRust By Example
intermediateModules

Modules

Organize code with modules and visibility.

Modules

Organize code with modules and visibility.

Difficulty

Intermediate

Code

rust
mod math {
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }

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

    fn secret() -> i32 {
        42
    }
}

fn main() {
    println!("add: {}", math::add(2, 3));
    println!("mul: {}", math::multiply(2, 3));
    // math::secret(); // error: function is private
}

Explanation

This example demonstrates how to use modules in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the modules category to build a complete understanding of this topic.

More Modules Examples