Sub topic 5
Splitting modules across files
This chapter assumes you can write inline mod blocks, know what pub does, and can run cargo build. Here you will move modules out of one file and into a directory layout that Cargo and the compiler follow.
A `mod` declaration loads a file
An inline module has a body in braces. A module declared with a semicolon has no body, so the compiler looks for the code in another file:
// src/lib.rs
pub mod geometry;The compiler searches for src/geometry.rs. It also accepts src/geometry/mod.rs, but you should not have both. The mod line is the only thing that adds a file to the crate. A file that no mod declaration mentions is never compiled, even if it sits in src/.
Nested modules use subdirectories
Say geometry has a child module shapes. You declare the child inside the parent's file:
// src/geometry.rs
pub mod shapes;The child's file goes in a directory named after the parent:
// src/geometry/shapes.rs
pub struct Square(pub u32);
impl Square {
pub fn area(&self) -> u32 {
self.0 * self.0
}
}The resulting layout is:
src/
lib.rs
geometry.rs
geometry/
shapes.rsThe module path crate::geometry::shapes maps directly onto the file path src/geometry/shapes.rs.
The two file styles
| Style | Files for module `geometry` with child `shapes` |
|---|---|
| Named file (current convention) | `geometry.rs` and `geometry/shapes.rs` |
| `mod.rs` (older style) | `geometry/mod.rs` and `geometry/shapes.rs` |
Both work, and you can use either style in one project. The named-file style avoids having many tabs titled mod.rs in your editor. Pick one and keep to it.
Using the split modules
Moving code to another file does not change paths or visibility. Items stay private to their module unless you mark them pub, and the pub on each mod line controls whether the module is visible outside its parent. A shorter public path is still possible with a re-export:
// src/lib.rs
mod geometry;
pub use geometry::shapes::Square;Users of the crate now write my_geometry::Square. Your file layout stays an internal detail.
Common errors
file not found for module(error E0583). The file is not at the path the declaration implies. Check the name and that a nested module's file is inside its parent's directory.file for module found at both ... and ...(E0761). You created bothgeometry.rsandgeometry/mod.rs. Delete one.module ... is private. Themod shapes;line lackspub, so code outsidegeometrycannot reach it.- Code seems ignored. The file exists but no
modline points at it, so the compiler never reads it.
Exercise
A package has src/lib.rs containing pub mod network;, and src/network.rs containing pub mod client;. Where must the code for client be stored, and what is its full path from the crate root?
Show answer
It goes in src/network/client.rs. Its path from the crate root is crate::network::client. If you preferred the older style, src/network/mod.rs would replace src/network.rs, but client.rs would still be at src/network/client.rs.