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

Modules organize code. Items are private by default.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

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

More Modules Examples