Sub topic 5
Splitting Modules Across Files
This chapter assumes you know how to declare inline modules with mod, use pub for visibility, and run cargo build. It covers how Rust maps the module tree onto files and directories, the two layouts you can choose from, and the errors people hit most often.
From inline modules to files
An inline module has its body in braces:
mod shapes {
pub struct Square(pub u32);
}A mod declaration with a semicolon and no body tells the compiler to load the body from another file:
mod shapes;The compiler looks for the file by name, relative to the file that contains the declaration. The module tree stays the same. Only the place where the source text lives changes.
The crate root
Every crate has one root file. Cargo uses src/lib.rs for a library and src/main.rs for a binary. The compiler starts reading at the root, and it only reads other files when a mod name; declaration points to them.
Creating src/geometry.rs does nothing by itself. The file is ignored until some module declares mod geometry;. This is the most common surprise for newcomers, and it explains why a new file can seem to have no effect.
Where the compiler looks
For a declaration mod name; inside a given file, the compiler checks two locations. The first is a file named after the module. The second is a mod.rs file inside a directory named after the module.
| Declaration is in | Looks for (modern layout) | Alternative (older layout) |
|---|---|---|
| `src/lib.rs` or `src/main.rs` | `src/geometry.rs` | `src/geometry/mod.rs` |
| `src/geometry.rs` | `src/geometry/shapes.rs` | `src/geometry/shapes/mod.rs` |
| `src/geometry/mod.rs` | `src/geometry/shapes.rs` | `src/geometry/shapes/mod.rs` |
The crate root is special. Its child modules sit directly in src/. For any other file, child modules go in a directory named after that file's module.
A worked example
Here is a small library with a nested module tree.
my_geometry/
├── Cargo.toml
└── src/
├── lib.rs
├── geometry.rs
└── geometry/
└── shapes.rsThe contents of the three source files:
// src/lib.rs
pub mod geometry;// src/geometry.rs
pub mod shapes;// src/geometry/shapes.rs
pub struct Square(pub u32);
impl Square {
pub fn area(&self) -> u32 {
self.0 * self.0
}
}The module tree is crate::geometry::shapes. External code reaches the type as my_geometry::geometry::shapes::Square.
Notice the two pub keywords on the mod lines. Without pub mod geometry; in lib.rs, code in other crates cannot name the module. Without pub mod shapes; in geometry.rs, only geometry and its descendants could name shapes. Splitting into files does not change visibility rules. A module is still an item, and its privacy is set by the mod declaration, not by the file.
Two layouts: `name.rs` and `name/mod.rs`
Before Rust 2018, a module with children had to use mod.rs:
src/geometry/mod.rs
src/geometry/shapes.rsSince the 2018 edition, you can put the module's own code in src/geometry.rs and its children in src/geometry/. Both layouts still compile, and they are equivalent as far as the module tree is concerned.
The modern layout is generally preferred because an editor with many open tabs can show several files that are all named mod.rs. Files named geometry.rs and shapes.rs are easier to tell apart.
Do not use both for the same module. If both src/geometry.rs and src/geometry/mod.rs exist, the compiler reports an ambiguity error (E0761). Pick one layout per module. A project can mix layouts across different modules, but consistency makes it easier to read.
Child modules inside a file
A module file can hold both its own items and its child module declarations. Suppose src/geometry.rs looks like this:
// src/geometry.rs
pub mod shapes;
pub const ORIGIN: (i32, i32) = (0, 0);
pub fn distance_from_origin(p: (i32, i32)) -> f64 {
let dx = (p.0 - ORIGIN.0) as f64;
let dy = (p.1 - ORIGIN.1) as f64;
(dx * dx + dy * dy).sqrt()
}The file contains the shapes declaration and ordinary items. The directory src/geometry/ holds only the children. This keeps related code together and avoids a file that exists only to list mod lines.
Inside shapes.rs, you can refer to the parent module with super:
// src/geometry/shapes.rs
use super::ORIGIN;
pub struct Square(pub u32);
impl Square {
pub fn area(&self) -> u32 {
self.0 * self.0
}
pub fn origin() -> (i32, i32) {
ORIGIN
}
}Paths in use declarations are resolved against the module tree, not against file paths. super::ORIGIN means "the ORIGIN item in the parent module", which happens to be defined in geometry.rs.
Mixing inline and file modules
A file module can contain an inline module, and an inline module can declare a file module. In the second case, the file path gets an extra directory for the inline module's name.
// src/lib.rs
mod outer {
pub mod inner;
}Here the compiler looks for src/outer/inner.rs. The inline outer has no file of its own, but it still adds a directory level. The #[path = "..."] attribute can override the lookup, but it is rarely needed and makes the layout harder to follow.
Common errors
- E0583, file not found for module. You wrote
mod shapes;but no matching file exists at either location. Check the table above, including the directory name. - E0761, multiple candidate files. Both
name.rsandname/mod.rsexist. Delete or merge one. - File ignored. You created a file but never declared it with
mod. The compiler does not scan directories. - Declared in the wrong place. Writing
mod shapes;inlib.rsmakes the compiler look forsrc/shapes.rs, notsrc/geometry/shapes.rs. The declaration must be in the parent module's file. - Private module.
mod geometry;withoutpubcompiles, but other crates cannot use it. Inside the crate, siblings and descendants of the parent can still reach it. - Declaring a module twice. Writing
mod shapes;in two places tells the compiler to load the same file as two different modules. This either errors or silently produces duplicate types that do not match. Declare each module once, and useusepaths elsewhere.
Choosing file boundaries
Not every module needs its own file. Reasonable guidelines:
- Start with an inline module or a single file. Split when a file becomes hard to navigate, often a few hundred lines.
- Give each file one clear responsibility, such as one major type with its
implblocks. - Keep small helper modules inline, especially
#[cfg(test)] mod tests, which normally sits at the bottom of the file it tests. - Make module names mirror the concepts in your domain, so that paths such as
geometry::shapes::Squareread naturally.
Splitting a file later is cheap. Moving code into a new module changes its path, so any use lines that name it must change too. Re-exporting from the parent with pub use can keep the old path working. The next chapter covers that technique.
Checking the layout
You can confirm that the compiler found every file by building the example:
cargo buildA missing file gives an E0583 error that names the paths it tried. To see the whole module tree, the third-party cargo-modules tool prints it, though it is not needed for the rest of this tutorial.
Exercise
A crate has src/lib.rs containing pub mod network; and a file src/network.rs containing pub mod client;. Where must the body of the client module live, and what error appears if you create both src/network/client.rs and src/network/client/mod.rs?
Show answer
The body can live in src/network/client.rs (modern layout) or src/network/client/mod.rs (older layout), because the declaration is in src/network.rs and children go in the src/network/ directory. If both files exist, the compiler reports error E0761, multiple candidate files for the module. Keep only one.
Exercise
You add src/geometry/circle.rs but your code cannot find geometry::circle. The file has no syntax errors. What is the most likely cause, and which file needs which line?
Show answer
The module was never declared. Add pub mod circle; (or mod circle; if it should stay private) to src/geometry.rs, or to src/geometry/mod.rs if you use that layout. The compiler only loads files that a mod declaration points to.