How to use a module from another directory?

How can I plug modules from src/modules into main.rs

You can do:

#[path = "modules/module_1.rs"]
mod module_1;
1 Like

In Rust, modules are a hierarchy, and directories and files are expected to match that hierarchy rather than having arbitrary separate organization. This means that if you currently have the files

src/main.rs
src/modules/foo.rs

then standard practice is to either move src/modules/foo.rs to src/foo.rs (placing it to be a child of the crate root main.rs), or create the intermediate module file src/modules.rs[1] which contains mod foo;, and put mod modules; in src/main.rs.

While you can override the directory structure using the #[path] attribute, you should not. Rust projects following the built-in code organization conventions is important for readability — it allows any Rust programmer to easily navigate an unfamiliar project.


  1. or src/modules/mod.rs, equivalently â†Šī¸Ž

7 Likes