Split a project into files
Quick answer
Separate a growing program into files when its responsibilities become distinct. The module tree determines how code is reached; moving a module into a file need not change its callers.
Declare modules explicitly
In src/main.rs, mod report; loads src/report.rs (or src/report/mod.rs, not both). crate:: starts at the current crate root. super:: starts at the parent module. The following file-writing commands are manual fixtures for a fresh local directory, not browser execution.
mod report { fn count() -> u32 { 4 } pub mod display { pub fn total() -> u32 { super::count() } }}fn main() { println!("{}", crate::report::display::total()); }Expected stdout (not executed):
4A child can access a private item in its parent.
cargo new lesson_filescd lesson_filesprintf '%s\n' 'mod report; fn main() { println!("{}", report::count()); }' > src/main.rsprintf '%s\n' 'pub fn count() -> u32 { 4 }' > src/report.rscargo runManual terminal step; not executed. Expected behavior (environment dependent):
Program prints 4.Only overwrite the files in the newly generated disposable package.
Common mistake
A source file is not automatically a module merely because it exists.
Try it yourself
Move count into a second module and update the path without changing the printed number.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Split a project into files — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Both src/report.rs and src/report/mod.rs exist for mod report. What should you do?
Split a project into files — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust mod report { fn count() -> u32 { 4 } pub mod display { pub fn total() -> u32 { super::count() } } } fn main() { println!("{}", crate::report::display::total()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Split a project into files — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```bash cargo new lesson_files cd lesson_files printf '%s\n' 'mod report; fn main() { println!("{}", report::count()); }' > src/main.rs printf '%s\n' 'pub fn count() -> u32 { 4 }' > src/report.rs cargo run ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.