tezvyn:

Rust's Module-to-Filesystem Mapping

AI-drafted, machine-checkedSource: doc.rust-lang.orgintermediate

Rust's module system maps directly to your file system. A `mod foo;` statement tells the compiler to look for `foo.rs` or `foo/mod.rs`. This is how you organize any multi-file Rust project.

WHY IT EXISTS To provide a clear, predictable way to organize large codebases without the ambiguity of include paths or complex build configurations. It lets the project's directory structure serve as a direct, navigable map of its logical module structure.

THE MENTAL MODEL Think of your file system as a direct reflection of your crate's module tree. The mod keyword is a promise to the compiler: "The code for this module exists at a specific file path relative to me." The compiler then knows exactly where to look, no configuration needed.

HOW IT WORKS When the compiler sees mod my_module; in a file (like src/lib.rs), it searches for the module's code in one of two locations: src/my_module.rs (the modern, idiomatic style) src/my_module/mod.rs (an older, but still supported, style)

This rule applies recursively. If src/my_module.rs in turn contains mod submodule;, the compiler will look for src/my_module/submodule.rs. The file and directory structure perfectly mirrors the module path. The mod keyword declares the module and tells the compiler to include its file. The use keyword, by contrast, brings paths into scope but does not affect which files are compiled.

WHEN TO USE IT This is the standard, built-in system for organizing any Rust project that grows beyond a single main.rs or lib.rs file. As your code grows, you extract logic into a new file and declare it with a mod statement. The idiomatic approach is to prefer module_name.rs files over the older module_name/mod.rs style.

WHEN NOT TO USE IT This file-based module system is fundamental to Rust, so you don't opt out of it. The main choice is which file-naming style to use. Avoid the mod.rs style in new projects. While allowed, it leads to having many files named mod.rs open in your editor, which is confusing. Mixing styles in one project is also allowed but strongly discouraged for clarity.

ONE CANONICAL EXAMPLE A library crate with a front_of_house module and a nested hosting submodule would have this file structure: src/lib.rs contains the line mod front_of_house;. The file src/front_of_house.rs contains the line pub mod hosting;. Finally, the file src/front_of_house/hosting.rs contains the functions for the hosting module. This file hierarchy directly mirrors the logical module path crate::front_of_house::hosting.

Read the original → doc.rust-lang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.