Rust's module system helps organize code into logical units, control privacy, and manage scope. Here's a comprehensive guide to all the use cases.

Basic Module Declaration

Inline Modules

Define modules directly in a file using the mod keyword:

mod math {
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
    
    fn private_helper() { // private by default
        // ...
    }
}

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

File-Based Modules

Rust maps modules to the filesystem:

src/
├── main.rs
├── math.rs          // mod math;
└── utils/
    ├── mod.rs       // mod utils;
    └── helpers.rs   // mod helpers; (inside mod.rs)

In main.rs:

mod math;    // looks for math.rs or math/mod.rs
mod utils;   // looks for utils/mod.rs or utils.rs

The use Keyword

Bringing Items into Scope

mod garden {
    pub mod vegetables {
        pub fn carrot() {}
        pub fn potato() {}
    }
}

// Different ways to use
use garden::vegetables::carrot;           // specific item
use garden::vegetables::{carrot, potato}; // multiple items
use garden::vegetables::*;                // glob import (use sparingly)

Renaming with as

use std::collections::HashMap as Map;
use std::io::Result as IoResult;

let map: Map<String, i32> = Map::new();

Re-exporting with pub use

Expose nested items at a higher level:

mod internal {
    pub mod deep {
        pub fn utility() {}
    }
}

pub use internal::deep::utility; // users can now call crate::utility()