Rust Module Files
A module file is a module whose code lives in its own file. Every address in the program stays exactly the same.
mod garden; loads src/garden.rs
Write the mod garden line in the crate root. Rust then looks for the code in src/garden.rs. Or, in the older style, in src/garden/mod.rs:
// src/main.rs
mod garden;A submodule follows its parent
A submodule follows its parent. A mod beds line inside src/garden.rs makes Rust look in src/garden/beds.rs. Or, in the older style, in src/garden/beds/mod.rs:
// src/garden.rs
pub mod beds;
// the beds code lives in src/garden/beds.rsCallers use the path, never the file name
Other files reach the code by its path, never by naming the file. Moving code to a new file changes nothing for callers: same tree, same paths, same pub rules:
println!("tomatoes = {}", crate::garden::beds::tomatoes());Both styles at once is an error
Use only one style for one module. Having both src/garden.rs and src/garden/mod.rs for the same module is a compile error:
// src/garden.rs AND src/garden/mod.rs both on disk:
// error[E0761]: file for module `garden` found at both "src/garden.rs" and "src/garden/mod.rs"Example
// In a real project these live in files:
// src/main.rs -> mod garden;
// src/garden.rs -> pub mod beds;
// src/garden/beds.rs -> the Tomato code below
// Here they are inline, so the example runs as one file:
mod garden {
pub mod beds {
#[derive(Debug)]
pub struct Tomato {}
}
}
use crate::garden::beds::Tomato;
fn main() {
let plant = Tomato {};
println!("growing {:?}", plant);
}Key points
- Declare each module with mod exactly once, in one place.
- mod is a declaration.
- It is not an include you repeat in every file that uses it.
- The src/garden.rs style keeps each file name clear, so most new projects pick it.
- A module file holds one module's code in a file of its own.
In this example, the comments show the real file layout. main.rs declares the garden module. garden.rs declares a public beds module. beds.rs holds the Tomato struct. Below the comments, the same tree is written inline, so the example runs as one file. garden holds beds. And beds holds a public Tomato. The use line brings Tomato in by its full path, crate::garden::beds::Tomato. main builds one and prints it with {:?}: growing Tomato. Split into files or kept inline, the tree and the path are identical — only the storage changes.
Note
The mod.rs style can leave you with many open tabs all named mod.rs.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
You write mod garden; in src/main.rs. Where does Rust look for the code?