0
0
Rustprogramming~5 mins

Why modules are used in Rust

Choose your learning style9 modes available
Introduction

Modules help organize code into smaller parts. They make code easier to read and reuse.

When your program grows and has many functions or variables.
When you want to keep related code together, like math functions in one place.
When you want to share code between different parts of your program.
When you want to avoid name conflicts by separating code into different spaces.
When you want to make your code easier to test and maintain.
Syntax
Rust
mod module_name {
    // code here
}

// To use items from the module:
use crate::module_name::item_name;

Modules are declared with the mod keyword.

You can access module items using use or by full path.

Examples
This example shows a simple module with a public function called from main.
Rust
mod greetings {
    pub fn hello() {
        println!("Hello from module!");
    }
}

fn main() {
    greetings::hello();
}
This module contains a function to add two numbers, used in main.
Rust
mod math {
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
}

fn main() {
    let sum = math::add(5, 3);
    println!("Sum is {}", sum);
}
Sample Program

This program defines a module tools with a greeting function. The function is called from main.

Rust
mod tools {
    pub fn greet(name: &str) {
        println!("Hello, {}!", name);
    }
}

fn main() {
    tools::greet("Alice");
}
OutputSuccess
Important Notes

Use pub to make functions or variables accessible outside the module.

Modules help avoid cluttering the main program with too much code.

Summary

Modules organize code into smaller, manageable parts.

They help reuse code and avoid name conflicts.

Use mod to create modules and pub to share items.