0
0
Rustprogramming~5 mins

Defining modules in Rust

Choose your learning style9 modes available
Introduction

Modules help organize your Rust code into smaller parts. This makes your code easier to read and manage.

When your program grows and you want to split code into separate files.
When you want to group related functions and types together.
When you want to control what parts of your code are visible outside.
When you want to avoid name conflicts by keeping code in separate spaces.
Syntax
Rust
mod module_name {
    // code here
}

// or in another file:
mod module_name;

Use mod to define a module inside the same file or to link to another file.

Module files should be named module_name.rs or placed in a folder module_name/mod.rs.

Examples
This defines a module named greetings inside the same file. The function hello is public so it can be used outside.
Rust
mod greetings {
    pub fn hello() {
        println!("Hello from the module!");
    }
}

fn main() {
    greetings::hello();
}
This shows how to define a module in a separate file called math.rs and use its public function.
Rust
// In main.rs
mod math;

fn main() {
    math::add(2, 3);
}

// In math.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
Sample Program

This program defines a module tools with a public function hammer. The main function calls it.

Rust
mod tools {
    pub fn hammer() {
        println!("Using the hammer");
    }
}

fn main() {
    tools::hammer();
}
OutputSuccess
Important Notes

Functions and items inside a module are private by default. Use pub to make them accessible outside.

Modules can be nested inside other modules for better organization.

Use cargo build or cargo run to compile and run your Rust programs with modules.

Summary

Modules organize code into separate parts.

Use mod to define or link modules.

Make items pub to use them outside the module.