Module (mod) (Rust)

A module organizes code within a crate into named, nestable namespaces. Modules control visibility — items are private by default and exposed with the pub keyword.

Rust

You declare a module with mod name { ... } inline, or mod name; to load it from a separate file (name.rs or name/mod.rs). Modules form a tree rooted at the crate, and you refer to items by path: crate::network::connect or a relative super::helper.

Everything in Rust is private by default. Mark items pub to expose them outside their module. The use keyword brings paths into scope so you can write short names instead of full paths, and pub use re-exports an item as part of your public API.

Modules are about code organization and encapsulation, not separate compilation — they all live inside one crate. Use them to group related functionality and to hide implementation details behind a clean public interface.

Syntax

mod math {
    pub fn square(n: i32) -> i32 { n * n }
}
use math::square;

Examples

Rust

mod geometry {
    pub fn area(w: f64, h: f64) -> f64 { w * h }
}

fn main() {
    println!("{}", geometry::area(3.0, 4.0));
}

Output:

12

Learn it in a lesson

See also

Back to the Dictionary